|
|||||||
![]() |
|
|
Thread Tools | Search this Thread | Display Modes |
|
|
#1 |
|
Solid State Member
Join Date: Mar 2009
Posts: 6
|
I'm reading up on and learning about pointers in C and have read that, if you want to create an array that you'll only know the length of at runtime, the correct way to do this is using malloc:
Code:
int *iptr; iptr = malloc(i * sizeof(int)); // i to be read in at runtime However, when mucking about and testing this out I found that the compiler (GCC) doesn't throw up any complaints when you use: Code:
int i;
scanf("%d", &i);
int test[i];
|
|
|
|
|
|
#2 |
|
Site Team
|
Needed, no. Preferred? Yes. By using malloc you can then later call "free" to clear the memory and open it for other uses making the system leaner overall.
The real difference here is what is returned by the system. By doing things like int test[i] you're just saying we have a bunch of items to put in a list and is not a true pointer to anything, just strait values. The malloc function returns the memory address of the location that will store element 0 (the first data point) of an array, string or whatever else it might be. By setting a pointer equal to the results of malloc, you're telling the system "Hey, start here when looking for data from this pointer".
__________________
"as a fanboy i refuse to admit it and will pull countless things out of my butt to disprove it" Team Thelegorm! Total Kills: 21 (i iz in uor profile, editsing your sigz) |
|
|
|
|
|
#3 | |
|
Site Team
Join Date: Jul 2009
Posts: 2,627
|
This is one of the very reasons why I don't recommend starting with languages such as C - the manual memory management can get confusing rather quickly!
Quote:
As an aside, I'm sure a few years ago when a power line was pulled down by a storm, sparked and caught fire, the key to the safety system not cutting in was a misplaced malloc / free that fell foul to this very bug. You can (and should) later call free to release the memory aquired by malloc, and this will prevent memory leaks. Calling malloc however is an absolute must - GCC won't throw up any warnings because in C reading and writing to random chunks of memory is a perfectly legal operation, just one that can cause a lot of bugs, pains and headaches later on if you don't know exactly what you're doing! This is why generally speaking, people don't use C anymore unless there's a damn good reason
__________________
Save the whales, feed the hungry, free the mallocs. |
|
|
|
|
![]() |
| Thread Tools | Search this Thread |
| Display Modes | |
|
|