c - 为什么指针导致非指针编译错误?

标签 c pointers struct compilation

我有以下代码:

#include <stdio.h>

struct datos_nut
{
    char nombre[17];
    float calorias;
    float proteinas;
    float colesterol;
    float fibradietetica;
};
struct datos_nut *p;

struct datos_nut (*frutos)[4]= &(struct datos_nut[4]){
    {"Aguacate", 2.33, 0.018, 0, 0.07},
    {"Almendra", 6.1, 0.187, 0, 0.143},
    {"Fresa", 0.35, 0.008, 0, 0.002},
    {"Berenjena", 0.22, 0.012, 0, 0.0137}
};

void main(void)
{
    p = *frutos;
    printf("%s",(*p)[3].nombre);
}

当我尝试编译时出现以下错误:

[Error] subscripted value is neither array nor pointer nor vector

在 printf() 行中。每当我使用 p 而不是 *p 时,它都能完美地编译和运行。

此外,如果我使用 (*frutos)[3].nombre 编译没有错误并且工作,它不应该使用 *p 工作吗?

谁能指出这里的问题是什么以及为什么它适用于 *frutos 但不适用于 *p?

我正在 Windows 10 中使用 DevC++ 尝试此代码。

最佳答案

p 是一个指针,因此自 arrays "decay" into pointers ,你只需要改变这个:

printf("%s",(*p)[3].nombre);

为此:

printf("%s",p[3].nombre);

关于c - 为什么指针导致非指针编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53107856/

相关文章:

C : How to copy char array to struct ifreq?

C sprintf缓冲区sigsegv错误

c - 在 xv6 中实现内核级线程

c - 在一个函数而不是另一个函数中访问同一内存时发生段错误

c - 有效地处理 c 中的文件

c - 为什么不能将静态结构指针初始化为变量的地址

c++ - 坏指针 : expression can not be evaluated while parsing tokens

c++ - 在 vector 中调用覆盖函数 (C++)

c - 头文件帮助和结构

c - 如何访问作为指针传递给函数的结构中定义的指针变量?