I just start learning C and found some confusion about the string pointer and string(array of char). Can anyone help me to clear my head a bit?
// source code
char name[10] = "Apple";
char *name2 = "Orange";
printf("the address of name: %p\n", name);
printf("the address of the first letter of name: %p\n", &(*name));
printf("first letter of name using pointer way: %c\n", *name);
printf("first letter of name using array way: %c\n", name[0]);
printf("---------------------------------------------\n");
printf("the address of name2: %p\n", name2);
printf("the address of the first letter of name2: %p\n", &(*name2));
printf("first letter of name2 using pointer way: %c\n", *name2);
printf("first letter of name2 using array way: %c\n", name2[0]);
// output
the address of name: 0x7fff1ee0ad50
the address of the first letter of name: 0x7fff1ee0ad50
first letter of name using pointer way: A
first letter of name using array way: A
---------------------------------------------
the address of name2: 0x4007b8
the address of the first letter of name2: 0x4007b8
first letter of name2 using pointer way: O
first letter of name2 using array way: O
so I assume that both name and name2 point to the address of their own first letter. then my confusion is(see the code below)
//code
char *name3; // initialize a char pointer
name3 = "Apple"; // point to the first letter of "Apple", no compile error
char name4[10]; // reserve 10 space in the memory
name4 = "Apple"; // compile errorrrr!!!!!!!!!!
I create a char pointer called name2 and name2 pointer to the first letter of "Apple" which is fine, then I create another array of char and allocate 10 space in the memory. and then try to use name4 which is an address points to the first letter of "Apple". As a result, I got a compile error.
I am so frustrated by this programming language. sometimes they works the same way. but sometimes they doesn't. Can anyone explain the reason and if I really want to create a string or array of chars in separated lines. how I can do that???
Many thanks...