【问题标题】:Setting array of pointers设置指针数组
【发布时间】: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 = &amp;table。
  • @ImTrying 做或不做,没有尝试 :D 你问错了问题。这里不需要双重间接指针。

标签: arrays c struct function-declaration double-pointer


【解决方案1】:

在这个赋值语句中

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: %s\n", sample_arr[i].name);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 2013-11-11
    • 1970-01-01
    相关资源
    最近更新 更多