0

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

2
  • 1
    Please take the Tour, learn to create an MCVE and consult your Rubber Duck. Commented Jan 6, 2017 at 18:11
  • pass by pointer with the length of the array struct Commented Jan 6, 2017 at 18:11

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Please don't just provide the code but explain what the mistake of the OP was.
Thank you Gabriel, that solved the problem and i also corrected for loop counter.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.