C: need help with pointers
First of all, it won't compile, the call to the 'f' function is wrong. You need to pass the address of the array but you try to take the address of the type.
int main() { const int n = 5; SomeStruct *theArray = NULL; f(&theArray, n); //Pass the address of theArray instance, not the type SomeStruct. }
(re)alloc takes the amount of memory to allocate in bytes. Your struct probably consists of more then a single byte, so you need to allocate n times the size of the struct bytes:
*dynArray = (SomeStruct *)realloc(*dynArray, sizeof(SomeStruct) * n);
Additionally, you should test if the memory allocation actually succeeded before attempting to use the memory. (re)alloc returns a NULL pointer on failure.
As for how to access the struct member, there's no really clean way. The canonical way would be:
(*dynArray)[n - 1].someMember //(*dynArray) dereferences the pointer to access the underlying array pointer //[n - 1] accesses the last element //For scanf you need to take the address of the member so it becomes: &((*dynArray)[n - 1].someMember)
If you need to access a lot of members this way it becomes ugly. One could create a intermediate pointer to the array element to access as a proxy to make things cleaner:
SomeStruct *proxy = &((*dynArray)[n-1]); //proxy now points to array member n - 1. scanf("%d", &proxy->someMember); printf("%d", proxy->someMember); //Cleaner and more readable for multiple accesses.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now