Home > Back-end >  How can I assign to new values to static array in C?
How can I assign to new values to static array in C?

Time:01-10

Please advise me on how best to redeclare the array fields with new values using memcpy. If there's a better/optimum way to redeclare, please let me know that as well.

Here's my sample code:

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

#define array_size(array) sizeof(array)/sizeof(array[0])

struct user_profile {
    const char *first_name;
    const char *second_name;
    unsigned int age;
};

int main() {
    struct user_profile fields[] = {
        {"david", "hart", 32},
        {"billy", "cohen", 24},
    };
    
    for (int i = 0; i < array_size(fields);   i) {
        printf("%s %s\n", fields[i].first_name, fields[i].second_name);
    }
    
    memcpy(fields, {{"zach", "roberts", 59}, {"mike", "fisher", 19}}, sizeof(fields));
    return 0;
}

CodePudding user response:

You can, but you do not do this properly.

  1. Using memcpy:
    memcpy(fields, (struct user_profile[]){{"zach", "roberts", 59}, {"mike", "fisher", 19}}, sizeof(fields));
  1. You can simply assign structures:
    fields[0] = (struct user_profile){"zach", "roberts", 59};
    fields[1] = (struct user_profile){"mike", "fisher", 19};

Both methods use compound literals

  •  Tags:  
  • c
  • Related