0

How can I add an array to a struct property in C? Here you have an example of what I want to accomplish:

#include <stdio.h>
#include <string.h>

typedef struct {
    char age;
    short number;
    int grades[10];
    char name[80];
    char address[120];
} Student;

Student s;

s.age = 23;
s.number = 10;
strcpy(s.name, "Jon");
strcpy(s.address, "Doe");

int oldGrades[10] = {1, 8, 2, 2, 4, 9, 9, 8, 4, 1};

s.grades = oldGrades; // Error: expression must be a modifiable lvalue

How can I add the array oldGrades to the property grades of my recently created object?

4
  • This has nothing to do with structs. Commented Nov 29, 2018 at 19:07
  • 2
    s.grades = oldGrades; --> memcpy(s.grades, oldGrades, sizeof(oldGrades)); Commented Nov 29, 2018 at 19:07
  • If number is a phone number and not an id then it should be a string. Commented Nov 29, 2018 at 19:08
  • As an addendum to the other comments, you could also wrap the grades array in its own struct. You can copy the contents of a struct from one to another with assignment. Not suggesting it is good design practice, but just another technically correct way to achieve it. Commented Nov 29, 2018 at 19:37

1 Answer 1

1

You can manually copy the array contents using for loop.

for(int i =0;i<10;i++)
s.grades[i] = oldGrades[i];

Or you can use memcpy.

memcpy(s.grades, oldGrades, sizeof(oldGrades))

c doesn't provide facility s.grades = oldGrades to copy array by assignment.

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

1 Comment

Introducing memcpy() way in this situation is a good solution but i think for()is better to a newbie.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.