【发布时间】:2014-10-24 05:44:16
【问题描述】:
我在这里标记了四个 printf 语句。我的问题是,在完成发生重新分配的函数 AddSub 后,应该分配给 struct sub *a 的 struct sub *temp 包含的地址在程序返回到我打印的函数 main 时不会得到反映struct sub *dstore 的地址。
第一个、第二个和第三个 printf 语句显示重新分配成功(printf 2 显示 temp 收到了新地址,print 3 显示该地址已分配给 a)。但是我很困惑为什么第四个 printf 显示不同。
struct sub {
char code[8];
float units;
char tag[101];
};
void AddSub(struct sub *a, struct cla *b, int *ctr){
char ecode[8], etags[101];
float eunits;
struct sub *temp = a;
scanf("%s %f %s", ecode, &eunits, etags);
if (!(AlIn(ecode) + UnCh(ecode, a, *ctr)))
{
if(*ctr)
{
printf("Before realloc: %p, %p\n", (void*)a, (void*)temp); /*1st*/
temp = realloc(a, (*ctr + 1) * sizeof(*a));
printf("After realloc: %p, %p\n", (void*)a, (void*)temp); /*2nd*/
}
if(!temp)
{
printf("Insufficient space.\n");
free(a); free(b);
exit(1);
}
else
{
if(*ctr)
{
a = temp;
printf("After AddSub readdress: %p, %p\n", (void*)a, (void*)temp); /*3rd*/
}
strcpy((a + *ctr) -> code, ecode);
(a + *ctr) -> units = eunits;
strcpy((a + *ctr) -> tag, etags);
printf("%s saved. ", (a + *ctr) -> code);
*ctr = *ctr + 1;
}
}
}
int main()
{
char com[14];
int subctr = 0, clactr = 0;
struct sub *dstore;
struct cla *cstore;
if (!(dstore = malloc(sizeof(struct sub))))
exit(1);
if (!(cstore = malloc(sizeof(struct cla))))
{
free(datastore);
exit(1);
}
while(1)
{
printf("INPUT> ");
scanf("%s", com);
if(strcmp(com, "ADD-SUBJECT") == 0)
{
AddSub(dstore, cstore, &subctr);
printf("Finished Addsub: %p\n", dstore); /*4th*/
}
else if (strcmp(com, "EXIT") == 0)
{
printf("Bye!\n");
free(dstore); free(cstore);
return 0;
}
else
printf("What?.\n");
}
}
【问题讨论】:
-
因为在 C 中,函数参数是按值传递的(它们被复制)。如果你给函数内部的参数赋值,它只会影响函数本地的副本,而不影响调用者本身的原始参数。