Should every variable declared as a pointer allocate memory?

Well, I'm new to C. I would like to know how my headline says.

Suppose I specify pointers as follows:

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

Then

  • Do I need to allocate memory for each variable before storing data in them?
  • Is there any special case when I do not need to allocate memory for them? for this I know one for the pointer char, strdup()which allocate memory, we should not care about it.
  • Any other suggestions are welcome.
+4
source share
4 answers

Pointers indicate things. It is up to you what you point them to.

  • : int * q; .

  • , : int x; int * q = &x;

  • : int * q = malloc(29);

+8

, - , . , , . ,

char *ptr; //Here you allocated memory for pointer variable.
ptr = malloc(sizeof(char)); // allocated memory for the data pointed by ptr

free()

free(ptr); // DE-allocates memory pointed by ptr and not variable ptr. 
+3

, ?

.

, aprogram, , , " ". arround . , . , , , .

 char const *Default = "Default User"
 char *username = NULL;
 username = getUser();   // here the name is allocated dynamically if it is present.
 if(username == NULL)
    username = Default;

sapce "Default User" , , .

, , , . , , . , , (, C64):

 char *BorderColor = 0xd020;
 *BorderColor = 0;
+2

, C - * . . , , . , .

-:

uint32_t x;
uint32_t *p = &x;
uint32_t array[10];
uint32_t *q = array;// equals to int *q = &array[0];

-:

#define NUM_MACRO   ((uint32_t) 10)
//we must free after we using. Or, perhaps we we will get a segment fault.
uint32_t *p = malloc(size(uint32_t) * NUM_MACRO); 
+1

All Articles