Reputation: 194
I have created a struct which stores an integer, and then in a method I set the integer to a value. However, when I try to access the value in any other method, I'm given a large value that isn't the same.
typedef struct thing {
int size;
arraylist** list; // defined elsewhere
} thing;
// Creates a thing
void create (thing* table) {
table = (thing *)malloc(sizeof(thing) * 8);
table->size = 1;
printf("%d", table->size); // prints 1
}
void another (thing* table) {
printf("%d", table->size); // prints a large number
}
void main() {
struct thing a;
create(&a);
printf("test: %d", (&a)->size); // prints a random large number, ex. 1667722352
another(&a);
}
Upvotes: 1
Views: 183
Reputation: 2261
You're overwriting a variable on the stack which giving you unexpected values later on.
In you're main function, you declare a struct thing
on the stack.
void main() {
struct thing a; // Stack allocated variable
create(&a);
printf("test: %d", (&a)->size); // prints a random large number, ex. 1667722352
another(&a);
}
All of the memory is already there, however you then take the address of the variable and pass that along to other functions. Now, you pass that address (by value) to create
, call malloc
and replace that reference. The address you've just assigned is not the address from the object on the stack. And, because you haven't actually initialized the object on the stack, you end up printing out garbage values.
I'm not sure what you're trying to do, but one way to fix this exact instance is by not malloc
ing new memory and just using what you have on the stack.
// Creates a thing
void create (thing* table) {
// table already has memory
table->size = 1;
printf("%d", table->size); // prints 1
}
Upvotes: 1
Reputation: 9962
You probably want another level of indirection:
typedef struct thing {
int size;
} thing;
// Creates a thing
void create(thing **table) {
*table = malloc(sizeof(thing) * size); // don't know what size is. 1?
(*table)->size = 1;
printf("%d", (*table)->size); // prints 1
}
void another(const thing *table) {
printf("%d", table->size); // prints a large number
}
void main() {
struct thing *a;
create(&a);
printf("test: %d", a->size); // prints a random large number, ex. 1667722352
another(a);
}
Upvotes: 1