I have the following code which simply prints out an introduction for a person’s name.
#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;
}
Produces the output
The person you are looking for is Bob Newmonson
However changing intro(a) to intro(&a) produces
The person you are looking for is �@ Newmonson
When I open the first attempt in GDB and break on line 10 I find the address of person=0x601010. Both the first name and last name are stored where I would expect, 0x04006b9 and 0x4006bd since they where declared earlier in the stack.
What gets me is when I run GDB with the changes made to intro(&a). The address of person is now 0x7fffffffffdd38, with the first name pointing to 0x601010 and the last name pointing to 0x4006db.
Can anyone help explain to be what is going on and why I can still access the proper address of the last name in the second test.
EDIT :
As everyone seems to keep asking about it the void * was for a threading portion of this code that I did not include.
It’s because
ais already pointer to aPersonstructure; thereforeintro(&a)passes a pointer to that pointer, butintro()treats it’s argument as a pointer toPerson.Also, if
intro()is intended to work on a Person, it should declare aPerson *argument, not avoid *.