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

Getting error when assigning value to an array inside the struct datatype in C

  struct student {
    char name[20];
    int age;
    float mobile;
    char address[20];
};
struct student Amit;
Amit.name[20] = "Sachin"; // I have mentioned the size still warning and unexpected result! why?

output:

$ gcc try.c
try.c: In function ‘main’:
try.c:12:17: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
s1.name[20] = "Sachin";
^
$ ./a.exe

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 :

// I have mentioned the size still warning and unexpected result! why?

You have not specify the size of the array. The size of an array is specified in its declaration. You have specified an index for the subscript operator to access an element of the array.

The expression

Amit.name[20]

has the type char, Moreover there is present an access to memory beyond the array because the valid range of indices for the array is [0, 19].

On the other hand, the expression with the string literal "Sachin" used as an assignment expression has the type char *.

So the compiler issues a message.

Arrays do not have the assignment operator.

Either you need to initialize the array when an object of the structure type is defined like

struct student Amit = { .name = "Sachin" };

Or after defining the object you can copy the string literal in the array like

#include <string.h>

//...

struct student Amit;
strcpy( Amit.name, "Sachin" );
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