This code works perfectly; as you can see here name
is a pointer. When I give a value to it, it is stored perfectly, but when I change the pointer to array the code breaks. Why do I need a pointer to store a string?
#include<stdio.h>
#include<stdlib.h>
struct student{
char *name;
int roll;
int clas;
}*ptr,stu;
void main(){
int i;
int n;
stu.roll=2;
stu.name = "sum";
printf("%d %s",stu.roll,stu.name);
}
But this doesn't:
#include<stdio.h>
#include<stdlib.h>
struct student{
char name[10];
int roll;
int clas;
}*ptr,stu;
void main(){
int i;
int n;
stu.roll=2;
stu.name = "sum";
printf("%d %s",stu.roll,stu.name);
}
You cannot assign to arrays. This doesn't have a meaning in C.
You want:
strcpy(stu.name,"sum");
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
)?
T
is storedNow, what is an array `T var[N]?
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?
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 (ie 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.