Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do every variable declared as pointer have to allocate memory?

Well, I am new to C. I would like to know as my title says.

Suppose I declare pointers as following,

char *chptr1;
char **chptr2;
int *i;
int **ii;
struct somestruct *structvar1;
struct somestruct **structvar2;

Then,

  1. Do I need to allocate memory for every variable, before storing data into them?
  2. Is there any special case when I do not need to allocate memory for them? for this I know one for char pointer, strdup() which allocate memory itself, we have not to care much about it.
  3. Any further suggestions are welcome.
like image 481
pmverma Avatar asked Dec 13 '13 10:12

pmverma


People also ask

Is memory allocated when a pointer is declared?

A pointer is a variable that contains an address in memory. In a 64 bit architectures, the size of a pointer is 8 bytes independent on the type of the pointer.

Does a pointer need memory?

Yes, a declared pointer has its own location in memory. In the example above, you have a variable, 'b', which stores the value "17".

Are pointers dynamically allocated?

Dynamic memory allocation is to allocate memory at “run time”. Dynamically allocated memory must be referred to by pointers. the computer memory which can be accessed by the identifier (the name of the variable).

How is memory allocated to a pointer type variable?

Using pointers to allocate spacemalloc(n) allocates n bytes of memory and returns the address of that memory, or NULL if the allocation failed. Allocated memory must have an address which can be reached from the value of a variable, otherwise we cannot access it and it gets "lost".


1 Answers

Pointers point at things. It's up to you what you make them point at.

  • You can leave them uninitialized and don't use them: int * q; That's a little silly.

  • You can make them point to something that exists: int x; int * q = &x;

  • You can store the address of dynamically allocated memory in them: int * q = malloc(29);

like image 119
Kerrek SB Avatar answered Sep 19 '22 01:09

Kerrek SB