1

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; } 
4
  • 1
    Your call of memcpy shall not compile in C because this record {{"zach", "roberts", 59}, {"mike", "fisher", 19}} is not an expression. Commented Jan 9, 2023 at 11:04
  • Could you please share how best to use memcpy in this scenario? Commented Jan 9, 2023 at 11:07
  • 3
    OT: It doesn't matter much but.... The title says "static array" but there isn't any static array in the code Commented Jan 9, 2023 at 11:23
  • I meant static array as in declaration/assignment that is not followed for dynamic array. I'm new to C, sorry for the confusion! Commented Jan 10, 2023 at 10:24

1 Answer 1

3

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

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

1 Comment

Thanks for the correction, I was looking for it. And how about when length of the fields is more than 10, do I have to peform assignment seperately from fields[0]...fields[10]? What will be the best option out of both?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.