Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Allocation char* and char[]

Tags:

c++

What is the difference between these two in terms of memory allocation.

char *p1 = "hello";  char p2[] = "hello"; 
like image 290
blitzkriegz Avatar asked Jan 13 '11 13:01

blitzkriegz


People also ask

What is the memory allocation for char?

First declare a pointer to a "char". Then ask (the system) for space to store your required number of values using malloc and then add elements to this "array". char * test; int num_of_elements = 99; test = malloc(sizeof(char) * num_of_elements); //test points to first array elament test[0] = 11; test[1] = 22; //etc.

How much memory does a char array take?

It occupies exactly 32 bytes of memory. Internally everything an address.

How do you allocate memory to the array of char pointers?

In C, the RAM should use the following code to allocate the two-dimensional array: *contents = (char**) malloc(sizeof(char*) * numRows); **contents = (char*) malloc(sizeof(char) * numColumns * numRows); for(i = 0; i < numRows; i++) (*contents)[i] = ( (**contents) + (i * numColumns) );

What is the difference between char pointer and char array?

For the array, the total string is stored in the stack section, but for the pointer, the pointer variable is stored into stack section, and content is stored at code section. And the most important difference is that, we cannot edit the pointer type string.


2 Answers

The first one creates a pointer variable (four or eight bytes of storage depending on the platform) and stores a location of a string literal there, The second one creates an array of six characters (including zero string terminator byte) and copies the literal there.

You should get a compiler warning on the first line since the literal is const.

like image 196
Nikolai Fetissov Avatar answered Sep 19 '22 23:09

Nikolai Fetissov


The first one is a non-const pointer to const (read-only) data, the second is a non-const array.

like image 20
Paul R Avatar answered Sep 18 '22 23:09

Paul R