What is the difference between these two in terms of memory allocation.
char *p1 = "hello"; char p2[] = "hello";
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.
It occupies exactly 32 bytes of memory. Internally everything an address.
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) );
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.
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
.
The first one is a non-const pointer to const (read-only) data, the second is a non-const array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With