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

struct string variable assignment in C

#include <stdio.h>

struct Student {
    char name[10];
    int age;
    double gpa;
};

int main(void)
{
    struct Student s1;
    s1.age = 20;
    s1.gpa = 4.3;
    s1.name[10] = "Tom";

    printf("%s", s1.name);

    return 0;
}

I know ‘strcpy’ function or other way to assign string. but Why doesn’t it work above code..?
Please help me.

Specially, s1.name[10] = "Tom";

Thanks.

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

>Solution :

There are few issues with this statement:

s1.name[10] = "Tom";

In C array (of length n) indexing starts with 0 and ends at n-1. Accessing any elements out side of 0 to n-1 (both inclusive) will cause undefined behaviour. s1.name[10] is out of bound access and not valid.

Another problem is that you cannot assign a string literal to an array using assignment operator except when it is used in the initializer. You have to use strcpy to copy a string literal to a char array. Make sure length of string literal must not exceed the size of the array (make sure there is a room for \0).

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