Reputation: 9
When i run this code i got this error : [Error] subscripted value is neither array nor pointer nor vector
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*Defined a data type named User with typedef*/
typedef struct User{
char firstName[50];
char lastName[50];
int phonenumber;
}user;
int main(int argc, char *argv[]) {
user users[2];/*users defined "user" type*/
strcpy(users[0].firstName,"furkan");
strcpy(users[1].lastName,"xxxx");
users[0].phonenumber = 1;
users[1].phonenumber = 2 ;
print_users(users);
return 0;
}
/*Function for printing user type users values*/
void print_users(user usr)
{
int j=0;
for(j=0;j<10;j++)
{
printf("%-10s%-20s%7d\n",usr[j].firstName,usr[j].lastName,usr[j].phonenumber);
}
}
I can make this function without typedef but i wonder if there is a way to make this happen
Upvotes: 0
Views: 81
Reputation: 311018
The function parameter
void print_users(user usr);
^^^^^^^
is a scalar object. You may not apply the subscript operator for a scalar object.
If you want that the function deals with an array then you should declare the function at least like
void print_users(user usr[]);
^^^^^^^^^^
Take into account that it is not clear why the function uses magic number 10.
for(j=0;j<10;j++)
^^^^^
At the same time in the main you declared an array of only two elements
user users[2];
Thus it will be correctly to declare the function like
void print_users(user usr[], size_t n );
and to use the variable n
in the loop
for(j=0;j < n;j++)
^^^^^
Correspondingly the function can be called like
print_users( users, 2 );
Upvotes: 1
Reputation: 1122
void print_users(user *usr)
this should be the parameters that your function receive, because inside your function you're acessing usr[j], so that means that usr need to be a pointer and not a structure itself.
ah, just to say, your for goes from 0 to 9 (10 positions), and your only allocated 2 positions.
Upvotes: 1