英文:
How can I assign to new values to static array in C?
问题
请告诉我如何使用memcpy重新声明数组fields
并赋予新值。如果有更好/更优的方法,请也告诉我。
以下是示例代码:
#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;
}
英文:
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;
}
答案1
得分: 3
- 使用
memcpy
:
memcpy(fields, (struct user_profile[]){{"zach", "roberts", 59}, {"mike", "fisher", 19}}, sizeof(fields));
- 你可以简单地赋值结构体:
fields[0] = (struct user_profile){"zach", "roberts", 59};
fields[1] = (struct user_profile){"mike", "fisher", 19};
这两种方法都使用了复合文字。
英文:
You can, but you do not do this properly.
- Using
memcpy
:
memcpy(fields, (struct user_profile[]){{"zach", "roberts", 59}, {"mike", "fisher", 19}}, sizeof(fields));
- 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论