Help - memory allocation in C
Hello all,
I am writing a program that requires a global array of pointers to char: Code:
char *target_mac[ 5 ]; Unless I am really messed up, I do not need to allocate memory to the array itself: Since it is an array of pointers, that is taken care of with the [5] in the declaration, i.e., I get five pointers to char with that. Right? And the allocation for each element does not matter at this point, because a pointer is just a memory location, and I've given myself five here. Each element needs to have memory allocated to it though...like this: Code:
for( x = 0; x < 5; x++ ) { Code:
+main() // allocate the memory to the array elements, pass ipAddr TIA. |
Right, you got it. -- memory for the array itself is allocated when you make your array declaration. That gives you five "boxes", each of which contains a pointer to char. As you say, it is your responsibility to make those pointers point to something useful before dereferencing them. If you do that, you can use them in other functions and then free them when your program is done.
|
You seem to understand arrays of pointers. I'm not sure what your code does so your little diagram is a little confusing :)
But basically you can do a few things with that array of char pointers. First, you could pass the whole array to a function, along with the number of elements in the array. The function could then read/modify the data and return. Second, you could pass a single element of the array to a function to be read/modified. You should see a clear distinction between passing a single element and passing the entire array. Remember, both would be passed as different types as well: Code:
void modify_array(char * arr[], int sz); /* modify_array(target_mac, 5); */ - lowpro2k3 |
It's also common to have the last pointer in the array be NULL; this way the function knows when it's at the last pointer without you passing a count. (e.g. the exec* functions)
|
All times are GMT -5. The time now is 04:09 PM. |