1

I have the following code:

#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);
}

When I try to compile it gives me the following error:

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

in the printf() line. Whenever I use p instead of *p it compiles and works perfectly.

Also if I use (*frutos)[3].nombre compile without errors and works, shouldn't it work using *p ?

Can someone point me out what the problem is here and why it works for *frutos but not for *p?

I'm trying this code using DevC++ in Windows 10.

MLuna
  • 35
  • 7
  • `struct datos_nut *p;` vs `struct datos_nut (*frutos)[4]`. These two declarations look nothing like each other. I wonder why the variables declared therein behave differently. Must be a conspiracy. – n. m. could be an AI Nov 01 '18 at 19:44
  • Why not use `struct datos_nut frutos[4]= {...}` instead of `struct datos_nut (*frutos)[4]= &(struct datos_nut[4]){...}` and after that you could do this: `p = frutos;`? – Denis Sablukov Nov 01 '18 at 20:07
  • @DenisSablukov I was trying to make sure that those structures were stored in the code segment. – MLuna Nov 01 '18 at 22:40

1 Answers1

0

p is a pointer, thus since arrays "decay" into pointers, you just need to change this:

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

to this:

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

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • Then why does it work with printf("%s",(*frutos)[3].nombre); and does not give me the same compilation error?, If I use printf("%s",(frutos)[3].nombre); then it tells me [Error] request for member 'nombre' in something not a structure or union. – MLuna Nov 01 '18 at 19:19
  • But @MLuna, `frutos` is an array, while `p` is only a pointer. Make sure you read really carefully the link I posted. – gsamaras Nov 01 '18 at 19:24