2
#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.

3
  • 1
    s1.name has only 10 elements starting from s1.name[0], so s1.name[10] is out-of-range and you must not access (no read nor write) there. Commented Jul 11, 2022 at 16:25
  • 2
    The syntax you're using only works for an initializer. For example, char name[10] = "Tom"; works because it declares and initializes the array. But char name[10]; name = "Tom"; won't work because arrays cannot be assigned. Commented Jul 11, 2022 at 16:28
  • @JWJ FWIW, s1.name = "Tom"; might make some sense in a future rev of C, but not today. Commented Jul 11, 2022 at 16:36

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

Comments

0

In this expression statement

s1.name[10] = "Tom";

the left side operand has the type char. Moreover in this expression s1.name[10] there is dereferenced pointer that points outside the allocated array.

The right side operand after the implicit conversion has the type char *.

So you are trying to assign a pointer to a non-existent element of the array.

Pay attention to that arrays do not have the assignment operator.

You could initialize the object of the structure type when it is defined like

 struct Student s1=
 {
    .name = "Tom",
    .age = 20,
    .gpa = 4.3
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.