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?

melpomene
  • 84,125
  • 8
  • 85
  • 148
Diogo Capela
  • 5,669
  • 5
  • 24
  • 35

1 Answers1

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.

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
  • 1
    Introducing `memcpy()` way in this situation is a good solution but i think `for()`is better to a newbie. – EsmaeelE Nov 29 '18 at 19:46