A pretty basic C question. Why do the following two commands result in the creation of strings that have different sizes?
As you can see below, method 1 creates a string with size 8 bytes and method 2 creates a string with size 5 bytes.
Am confused as to why method 1 is creating a string of size 8 bytes...
(I've already seen these posts: Difference of sizeof between char* x and char x[] and What is the difference between char s[] and char *s?. Unless I had a reading-comprehension-fail, it doesn't really address why method 1 creates a string of size 8 bytes... According to the responses, it would seem that method 1 should be creating a pointer of size 4 bytes.)
Method 1:
char *string = "ABCD";
Method 2:
char string2[5] = "ABCD";
For example, when I run the following program, I get the output shown below.
#include <stdio.h>
int main(int argc, char *argv[])
{
char *string = "ABCD";
printf("Based on \"char *string = \"ABCD\":\n");
printf("Size of string: %ld\n",sizeof(string));
printf("Size of each element of string: %ld\n",sizeof(string[0]));
printf("String: %s\n\n", string);
char string2[5] = "ABCD\0";
printf("Based on \"char string2[5] = \"ABCD\":\n");
printf("Size of string: %ld\n",sizeof(string2));
printf("Size of each element of string: %ld\n",sizeof(string2[0]));
printf("String: %s\n\n", string2);
return 0;
}
Output of the above program: