【发布时间】:2021-11-14 10:29:52
【问题描述】:
我正在做一个小练习来加载一个指针数组(双指针)到一个结构。我在头文件中有如下定义:
#include <stdio.h>
#define LEN (5)
typedef struct sample_s {
int num;
char *name;
}sample_t;
typedef struct new_sample_s {
char *string;
sample_t **sample_arr;
}new_sample_t;
sample_t table[LEN] = {
{0, "eel"},
{1, "salmon"},
{2, "cod"},
{3, "tuna"},
{4, "catfish"}
};
并使用此 .c 文件中的定义:
#include "test.h"
void print_new_sample_array(sample_t **sample_arr) {
int len = sizeof(table)/sizeof(new_sample_t);
for(int i = 0; i < len; i++){
printf("The array element is: %s\n", sample_arr[i]->name);
}
}
int main() {
new_sample_t new_sample;
new_sample.sample_arr = table;
print_new_sample_array(new_sample.sample_arr);
return 0;
}
我有两个问题:
首先我不确定如何将table 正确加载到new_sample.sample_arr
这里的错误信息:
test.c: In function ‘main’:
test.c:13:27: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
new_sample.sample_arr = table;
^
其次,我不确定如何引用sample_arr 中每个元素的属性。例如,当我执行以下操作时,程序报错:
for(int i = 0; i < LEN; i++){
printf("This is the elem in the array: %s", new_sample[i]->name);
}
我正在尝试更多地了解双指针概念以及我做错的原因。我真的很感激答案将sample_arr 保留为双指针
谢谢!
【问题讨论】:
-
"首先我不确定如何正确将表加载到 new_sample.sample_arr 此处的错误消息:" => 你不知道,@987654329 的 type @ 是错的。试试
sample_t *sample_arr;。 -
@AnttiHaapala 我想一个更好的问题应该是如何加载双指针数组。因为我正在努力学习。我用
sample_t *sample_arr测试过,它确实有效,但不一定能帮助我理解双指针:) -
你需要从一个指针数组开始,例如
char *table[] = {"cod", "tuna"};你拥有的是struct的数组。 -
new_sample.sample_arr是指向sample_t结构的指针,而table是指向一堆sample_t结构的指针。我建议类似new_sample.sample_arr = &table。 -
@ImTrying 做或不做,没有尝试 :D 你问错了问题。这里不需要双重间接指针。
标签: arrays c struct function-declaration double-pointer