Lots of little things working against you in this code, eg the following...
int i = 0, n=5;
struct student s1[n];
...creates a variable length array of struct student
, preventing an initializer from being a viable path. But if for the sake of illustration you can live with a non-VLA version, then try this:
//Use a hard-coded to `5`, to create an array of 5 struct student, initialized as shown:
struct student s1[5] = {{"name1"1, 1.0},("name2",2,2.0},{"name3",3,3.0},{"name4",4,4.0},{"name5",5,5.0}};
Next, your current code: char nam[50];
creates a single uninitialized char array, sufficient for containing only 1 string with up to 49 characters, with a terminating \0
. If you can, create it like this. (for the sake of learning to copy strings in a loop.)
char nam[5][50] = {{0}};//created 5 elements of null terminated char array elements,
Then you can do this in your loop:
for(i=0;i<n;i++)
{
strcpy(nam[i], s1[i]name);
}
By now (from comments and answers) you should already know that strings cannot be copied using the =
operator like integers or floating numbers. String functions such as strcpy()
, or sprintf()
can be used to populate strings.