How to assign a string to struct variable in C?

I am unable to figure out how to assign a string to a struct variable using only <stdio.h> header file.

The following code gives me an error and I am unable to fix it.

#include <stdio.h>
 struct Student
{
    char name[50];
};
int main()
{
   struct Student s1;
   printf("Enter studen's name:\n");
   scanf("%s",s1.name);
   printf("Name : \n",s1.name);
   s1.name={"Hussain"};
   printf("Name : \n",s1.name);
}

It gives the following error while compilation:

test.c: In function 'main':
test.c:12:12: error: expected expression before '{' token
    s1.name={"Hussain"};
            ^

I have tried initializing it in the following way:
s1.name="Hussain";
But this doesn’t work too.
I could avoid this by the use of pointers as follows:

#include <stdio.h>
 struct Student
{
    char *name;
};
int main()
{
   struct Student s1;
   printf("Enter studen's name:\n");
   scanf("%s",s1.name);
   printf("Name : %s\n",s1.name);
   s1.name="Hussain";
   printf("Name : %s\n",s1.name);
}

This code works perfectly fine with no errors.
But I want to know where exactly I am doing wrong with the array, which is making my code not work.

>Solution :

Arrays do not have the assignment operator. So these assignment statements

s1.name = { "Hussain" };
s1.name = "Hussain";

are invalid.

You could use the standard C string function strcpy to copy elements of the string literal to the array s1.name like

#include <string.h>

//...

strcpy( s1.name, "Hussain" );

If you may not use standard string functions then you need to write a loop as for example

const char *p = "Hussain";

for ( char *t = s1.name; ( *t++ = *p++ ) != '\0'; );

Or

for ( char *t = s1.name, *p = "Hussain"; ( *t++ = *p++ ) != '\0'; );

Pay attention to that the second your program has undefined behavior. The pointer s1.name is not initialized and does not point to a valid object of an array type. So the call of scanf in this code snippet invokes undefined behavior.

struct Student s1;
printf("Enter studen's name:\n");
scanf("%s",s1.name);

Leave a Reply