gpt4 book ai didi

c - 将静态数组分配给另一个数组

转载 作者:行者123 更新时间:2023-11-30 17:43:07 25 4
gpt4 key购买 nike

#include<stdio.h>

struct test_ {
char *device_name;
char *path_name;
};

typedef struct test_ test_t;

struct capabilities_ {
test_t tab[3];
int enable;
};

static test_t table[3] = {
{ "first", "john"},
{ "second", "mike"},
{ "third:", "vik" },
};

int main()
{
struct capabilities_ cap;
//cap.tab = table; ???
return 0;
}

我有一个带有值的静态数组,我想将其分配/复制到表结构下相同类型/大小的变量到 cap.tab。您能帮忙看看如何做到这一点吗?

最佳答案

要在运行时执行此操作,您可以使用 user9000 的方法,或类似的方法:

for (i = 0; i < 3; i++)
cap.tab[i] = table[i];

或者,将您的选项卡转换为使用指向 test_t 的指针,而不是 test_t 数组。

struct capabilities_ {
test_t *tab;
int enable;
};

int main()
{
struct capabilities_ cap;
cap.tab = table;
printf("%s\n", cap.tab[1].device_name);
return 0;
}

或者,如果您尝试在初始化时执行此操作,请使用以下选项之一:

struct capabilities_ cap = {
{
{ "first", "john" },
{ "second", "mike" },
{ "third:", "vik" },
},
1
};

或者这个,

struct capabilities_ cap = {
{
table[0],
table[1],
table[2],
},
1
};

关于c - 将静态数组分配给另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20303798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com