Click to See Complete Forum and Search --> : Why doesnt this C Code Work


digitalzero
04-05-2002, 01:15 AM
#include <stdio.h>

struct Person
{
int age;
};

struct Person *getAge();

int main()
{
struct Person *p;
p = getAge();
printf("Age: %d\n",(*p).age);
return 0;
}

struct Person *getAge()
{
struct Person *result;

(*result).age = 10;

return result;
}


It compiles fine but when your run it: Age is -1929102879 or something

goon12
04-05-2002, 01:25 AM
hrm.. Not too sure but you could try:


printf("Age: %d\n", p->age);

instead of

printf("Age: %d\n",(*p).age);

digitalzero
04-05-2002, 01:29 AM
Still the same problem... after changing that

Energon
04-05-2002, 01:39 AM
You have to allocate memory for your pointer in getAge(). try:


struct Person* getAge()
{
struct Person* result = (struct Person*)malloc(sizeof(struct Person));

result->age = 10;
return result;
}


Also note the use of the ->, which derefernces the pointer so you don't need the (*result) to dereference.

bwkaz
04-05-2002, 09:37 AM
And then remember to:

free(p);

in main() after you print the stuff out.

Actually, I'm surprised it didn't segfault on you...

TheLinuxDuck
04-05-2002, 09:44 AM
Originally posted by bwkaz:
<STRONG>Actually, I'm surprised it didn't segfault on you...</STRONG>

It prolly didn't segfault because it's only overwriting 4 bytes. Sometimes it will let us get away with that, if it's a tiny amount. That, of course, also depends on where the pointer points to... (^=

bwkaz
04-05-2002, 09:32 PM
Yeah, I suppose. It would definitely have segfaulted if the pointer was initialized to NULL, but if the random value in memory happened to be valid in the process' address space, then I guess it'd be valid.