passing typdef struct as a parameter to the function


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; 

int main(int argc, char *argv[]) {

    user users[2];/*users defined "user" type*/



    users[0].phonenumber = 1;

    users[1].phonenumber = 2 ;


    return 0;

/*Function for printing user type users values*/
void print_users(user usr)
    int j=0;


I can make this function without typedef but i wonder if there is a way to make this happen

Show source
| function   | C   | struct   | typedef   2017-01-06 19:01 2 Answers

Answers to passing typdef struct as a parameter to the function ( 2 )

  1. 2017-01-06 19:01
    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.

  2. 2017-01-06 19:01

    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.


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

Leave a reply to - passing typdef struct as a parameter to the function

◀ Go back