[英]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;
}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 我可以不使用typedef来实现此功能,但我想知道是否有办法实现此目的
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. 这应该是函数接收的参数,因为在函数内部您访问的是usr [j],因此这意味着usr需要是一个指针,而不是结构本身。
ah, just to say, your for goes from 0 to 9 (10 positions), and your only allocated 2 positions. 嗯,就是说,您的for从0上升到9(10个职位),而您仅分配了2个职位。
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. 考虑到尚不清楚该函数为何使用魔术数字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 并在循环中使用变量
n
for(j=0;j < n;j++)
^^^^^
Correspondingly the function can be called like 相应地,函数可以像
print_users( users, 2 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.