![]() |
| ||
| changing values of a struct Hello, i'm still trying to learn C, and I have a new question ;). I want to declare a struct, and use a function to manipulate the entries. If I change the values within a function it's ok; however, when i access the members outside the function, they're not defined anymore. How do i change the values in the struct such that a different function can use it as well? I thought using a pointer to struct would be 'good enough', but apparently it isn't ;). Thanks in advance, #include <stdio.h> |
| ||
| Re: changing values of a struct Quote:
name[i].x=drand48()*20; You are assigning to a field of a structure, but that is not a field of a structure. It is a pointer to a field of a structure. It can be done in two ways: (*name[i]).x = drand48() * 20; or name[i]->x = drand48() * 20; Same thing is going on with the others and even with the parameters in the printf(); |
| ||
| Re: changing values of a struct I tried changing the function like that as well; but it still doesn't work. Maybe I'm silly, but I just don't see it. (and thanks for helping) void initialpos(struct atom *name, int N) |
| ||
| Re: changing values of a struct >but it still doesn't work. What's not working?. What's supposed to happen and it isn't?. You forgot to change the arguments also in the printf(). |
| ||
| Re: changing values of a struct Now it's like this: void initialpos(struct atom *name, int N) (i forgot the printf function the previous time). Now it's complaining about 'invalid type argument of '->' ' I'll explain what i want to do. In main() a the function initialpos() is called, to give a particle some initial position. But this position is needed later on as well, so i want to keep the values too when the function is finished. When i did it like in the opening post, the values are written to the struct, but after the function is fnished, the elements are gone. Hope you understand what I mean. Thanks for the help so far, |
| ||
| Re: changing values of a struct Needs some changes: initialpos(&patom[0],N); instead of initialpos(patom[0],N); the & is needed if you want to pass it the address of a structure. void initialpos(struct atom *name[], int N) instead of void initialpos(struct atom *name, int N) *name[] is the beginning of the array of structures. |
| ||
| Re: changing values of a struct Thanks! it's working now. It makes sense: before I only gave one element as an argument, but instead I had to give an array with starting address &patom[0]. Now all variables in the struct are kept (because the array in the argument). I'd never think of that! (even though it makes sense now). Thanks a lot! Now I can finally go to bed.. it's 2 AM here ;). (If something doesn't work, I keep wondering how to solve it... and then I can't sleep. ) Thanks again! |
| All times are GMT -4. The time now is 11:44 am. |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC