Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading