我有下面的代碼,它只是打印出一個人的名字的介紹。C指針參考
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char* firstname;
char* lastname;
}Person;
void intro(void *person){
printf("The person you are looking for is %s %s\n", ((Person *)person)->firstname, ((Person *)person)->lastname);
}
int main()
{
Person *a = NULL;
a = (Person *)malloc(sizeof(Person));
char *first = NULL, *last = NULL;
first = (char *)malloc(sizeof(char)*20);
strncpy(first,"Bob", 20);
last = (char *)malloc(sizeof(char)*20);
strncpy(last,"Newmonson", 20)
a->firstname = first;
a->lastname = last;
intro(a);
return 0;
}
產生輸出
The person you are looking for is Bob Newmonson
但是改變intro(a)
到intro(&a)
產生
The person you are looking for is �@ Newmonson
當我打開GDB的第一次嘗試,並在第10行打破我找到地址person=0x601010
。名字和姓氏都存儲在我預期的地方,0x04006b9
和0x4006bd
,因爲它們是在堆棧中早些時候聲明的。
什麼讓我是當我運行GDB與intro(&a)
的變化。 person
的地址現在是0x7fffffffffdd38
,第一個名字指向0x601010
,姓氏指向0x4006db
。
任何人都可以幫助解釋是怎麼回事,爲什麼我仍然可以在第二次測試中訪問姓氏的正確地址。
編輯:
至於大家似乎一直在問關於它的void *
是這個代碼,我沒有包括的螺紋部分。
FYI:'第一=(的char *)malloc的(的sizeof(char)的* 20);第一個=「鮑勃」;「沒有做你認爲正在做的事情。 –
另外,爲什麼當聲明'intro()'是否只有一個''* *'的時候,有一個希望與它一起工作的'void *'? –
@MichaelBurr我想用'void *'來進行練習,但碰到了這個問題。 – Blackninja543