#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct contact {
char name[30];
int phone_number;
char address [30];
};
int main(int argc, char **argv) {
struct contact friend;
strcpy(friend.name, "Jane Doe");
friend.phone_number = 377177377;
strcpy(friend.address, "3771 University Avenue");
char *name;
int number;
char *address;
update_contact(&friend, name, number, address);
return 0;
}
我需要实现update_contact
函数来更新联系人信息。 friend
和 number
是普通变量。 *name
和*address
是指针。但是函数调用也使用了指针friend
的地址,即&friend
。现在我很困惑我应该在函数参数中放什么。
我试着把指针放进去。
void update_contact (struct *c, char *name, int number, char *address) {
c->name = name;
c->phone_number = number;
c->address = address;
}
然而,这会带来一堆错误,比如
error: request for member 'address' in something not a structure or union
&c->address = address;
我该如何解决这个问题?谢谢
这是固定版本。感谢 Thomas Jager 和 Some Name。
void update_contact (struct contact *c, char *name, int number, char *address) {
strcpy(c->name, name);
c->phone_number = number;
strcpy(c->address, address);
}
最佳答案
正如 David C. Rankin 所建议的:
您需要初始化作为参数传递的变量。 例如
char *name = "Donald Trump";
int number = 01010101010;
char *address = "White House;
char name[] = "Donald Trump";
int number = 01010101010;
char address[] = "White House;
或者你可以在调用函数时使用字面量和常量
update_contact(&friend, "Donald Trump", 0101010010, "White House");
void update_contact (struct contact *c, char *name, int number, char *address) {
strcpy(c->name, name);
c->phone_number = number;
strcpy(c->address, address);
}
关于c - 如何确定在函数参数中使用指针或普通变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54390580/