C语言 设置指针数组



我正在做一个小练习来加载一个指针数组(双指针)到一个结构体。我在头文件中有以下定义:

#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: %sn", 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;
}

我有两个问题:

首先,我不确定如何正确加载tablenew_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 = table;

右操作数(在将数组隐式转换为指向其第一个元素的指针之后)的类型为sample_t *,而由于数据成员

的声明,左操作数的类型为sample_t **
sample_t **sample_arr;

没有从sample_t *类型到sample_t **类型的隐式转换。所以编译器发出一条消息。

你应该像 那样声明数据成员
sample_t *sample_arr;

对应的函数声明看起来像

void print_new_sample_array(sample_t *sample_arr);

在函数中printf的调用看起来像

printf("The array element is: %sn", sample_arr[i].name);

最新更新