如何在C中为静态数组分配新值?

huangapple go评论50阅读模式
英文:

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 &lt;stdio.h&gt;
#include &lt;string.h&gt;

#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[] = {
        {&quot;david&quot;, &quot;hart&quot;, 32},
        {&quot;billy&quot;, &quot;cohen&quot;, 24},
    };
    
    for (int i = 0; i &lt; array_size(fields); ++i) {
        printf(&quot;%s %s\n&quot;, fields[i].first_name, fields[i].second_name);
    }
    
    memcpy(fields, {{&quot;zach&quot;, &quot;roberts&quot;, 59}, {&quot;mike&quot;, &quot;fisher&quot;, 19}}, sizeof(fields));
    return 0;
}

答案1

得分: 3

  1. 使用 memcpy
    memcpy(fields, (struct user_profile[]){{"zach", "roberts", 59}, {"mike", "fisher", 19}}, sizeof(fields));
  1. 你可以简单地赋值结构体:
    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.

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

Both methods use compound literals

huangapple
  • 本文由 发表于 2023年1月9日 19:01:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75056332.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定