You don't need to use a pointer to store strings. Arrays are pointers are two valid ways to deal with strings, and they are some way mutually bound with each other. You just need to understand what an array is and how are characters stored in them so that we can call them "strings".
First thing we need to remember: what is a pointer (to a type T)?
- It the address where data of type
T is stored
Now, what is an array `T var[N]?
- It is a sequence of N elements of the same type
T stored contiguously in memory.
var is the name of the array, and represents the address of its first element of the array. It is evaluated like a pointer though it's not a pointer.
Almost there. What is a string?
- it is an array containing elements of type
char terminated by a special nul-terminator character (`'\0')
So a string IS an array, but like every array can be evaluated as a pointer to its first element. And every pointer to char is a string if it is terminated by the null character, and be accessed with the array syntax:
char * str = "hello"; // contains 'h', 'e', 'l', 'l', 'o', '\0'
// cannot be modified because it points to a constant area of memory
printf ("%c %c\n", str[1], str[4]); // prints "e o"
/********/
char str2[] = "hello"; // same contents as above, but thi one can be modified
Note: the assignment
stu.name = "sum";
is invalid because name is an array field of the struct student struct. As explained above an array is not a pointer, and one of the main differences is that it cannot be assigned (i.e. cannot be an lvalue in an assignment action). It will raise a compilation error.
The correct action is copying the data into the array using strcpy() function.
char name[] = "John";is not an assignment. It is an initialization. Syntactically, it is a short cut forchar name[5] = { 'J', 'o', 'h', 'n', '\0'}. There is no similar syntactic sugar forchar name[5]; name = "John";That is just a syntax error. You have to writechar name[5]; strncpy( name, "John", sizeof name);void main(){Per the C standard, there are only two(2) valid signatures formain()they are:int main( void )andint main( int argc, char *argv[] )