Domanda

I am a new C developer. I have been programming in Java for 3 years now. I noticed the manual memory allocation I have to do in C.

However, it is still ambiguous to me when it comes to pointers and memory allocation. I will say what I understand and please if anyone has any comment on what I have to say, please correct me.

So let's say I have:

int *a;

So what this does is creates a pointer called a that points to an integer value.

int *a = address;

If I print address, I will get the address.

Let's say I want the value, I do what we call dereferencing and

int *a = *value;

If I print value in this case, I would get the actual number stored in memory.

I noticed in the ebook I am using, that sometimes, we allocate memory in the heap. Is it always the case? Everytime I need to use a pointer for a string for example using char*, I have to use alloc() and sizeof() to respectively allocate memory according to the size of the intended type?

È stato utile?

Soluzione

OK. Pointers for the Java guy.

When you declare

int *a;

it is the same as in Java doing:

Integer a;

Java does not have pointers, but all objects are held by references. So,

Integer a = new Integer(3);

is the same as:

int *a = malloc(sizeof(int)); 

in C.

Now, Java does not have an & operator, and you cannot do pointer arithmetic, but references really are roughly the same otherwise.

To answer your questions:

  • does it always have to come from the heap?

No. In C you can point a pointer at something that is already allocated on the stack (or anywhere else in RAM, such as a DMA register for doing hardware interactions):

void f() {
   int i;
   int *a = &i;
   *a = 3; // same as i = 3

   a = (int*)0x12340000; // some address in memory, possibly screen RAM?
   *a = 0xffffffff; // possibly set some colors on the screen
}
  • Do I have to use malloc and sizeof every time to allocate space?

If you do use malloc, then yes, you have to specify how much space you want. But you can just as easily ask the compiler to allocate the space in static data space:

void f() {
   char *p = "hello";
   ....
}

In this case, the literal string typically becomes part of the compiled program, and is placed in a statically allocated spot at program startup by the OS.

Altri suggerimenti

int *a = *value;

This is incorrect unless value is declared to be an int **:

int **value;

Below is a sequence of using an int pointer with appropriate comments:

int num1;          // Declare an int
int num2;          // Declare a different int
int *pNum = &num1; // Declare an int pointer and set its value to the address of num1
*pNum = 6;         // Set the value of num1
pNum = &num2;      // Change value of int pointer to the address of num2
*pNum = 10;        // Set the value of num2
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top