Reputation: 15
this is the code. the function "leggi" is supposed to read the value of c[i].a but when I type the first number in the console the program crashes. It's probably a pointers issue but i can't figure it out
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct cane{
int a;
}cane;
void leggi(cane *c[20]){
int i;
for(i=0;i<5;i++)
scanf("%d", &c[i]->a );
}
int main(){
int i;
cane c[20];
leggi(&c);
for(i=0;i<5;i++)
printf("%d",c[i].a);
return 0;
}
Upvotes: 0
Views: 145
Reputation: 238341
The type of &c
is cane (*)[20]
i.e. a pointer to an array. You've declared the argument of the function to be cane *[20]
which is (as a function argument) a cane**
which is a pointer to a pointer.
You may have intended to pass a pointer to an element of the array instead:
void leggi(cane *c)
// ...
scanf("%d", &c[i].a );
//
leggi(c);
Or possibly you really intended to pass a pointer to the array instead:
void leggi(cane (*c)[20])
scanf("%d", &(*c)[i].a )
//
leggi(&c);
Upvotes: 1
Reputation: 2813
You pass the wrong type to the function.
If you want to pass an array to a function the array name decays to a pointer to its first element, therefore the argument is only a pointer to the type:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct cane{
int a;
}cane;
void leggi(cane *c){
int i;
for(i=0;i<5;i++)
scanf("%d", &(c[i].a) );
}
int main(){
int i;
cane c[20];
leggi(c);
for(i=0;i<5;i++)
printf("%d",c[i].a);
return 0;
}
Upvotes: 3