Home > front end >  Getting error when assigning value to an array inside the struct datatype in C
Getting error when assigning value to an array inside the struct datatype in C

Time:12-21

  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 ☺

CodePudding user response:

// 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" );

CodePudding user response:

name[20] is the char at index 20 of the name (out of bounds, by the way), and you're trying to assign a string to it. Instead, you could copy the value there using strcpy:

strcpy(Amit.name, "Sachin");
  • Related