#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stu
{
char name;
char g;
int score;
}STU;
void f(char p)
{
p=(char)malloc(10);
strcpy(p,"qian");
}
void main()
{
struct stu a={NULL,'m',290},b;
a.name=(char)malloc(10);
strcpy(a.name,"zhao");
b=a;
f(b.name);
b.g='f';
b.score=350;
printf("%s%c%d\n",a.name,a.g,a.score);
printf("%s%c%d",b.name,b.g,b.score);
}
为什么a.name和b.name输出都是zhao,在f函数中不是改变了吗?
void f(char* p)函数形参只是值传递,修改如下,供参考:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
struct stu
{
char* name;
char g;
int score;
};
void f(char** p) //修改
{
(*p) = (char*)malloc(10);
strcpy((*p), "qian");
}
void main()
{
struct stu a = { NULL,'m',290 }, b;
a.name = (char*)malloc(10);
strcpy(a.name, "zhao");
b = a;
f(&b.name); //修改
b.g = 'f';
b.score = 350;
printf("%s %c %d\n", a.name, a.g, a.score);
printf("%s %c %d", b.name, b.g, b.score);
}