How can I return a string from a function?
quote:Original post by Anonymous Poster
int blah[80];
Type: int*
Significance: It''s a pointer to the first element in the array (if it were a character array, it''s be the first character in the string). The array is a linear block of memory which, in this case, is 80 consecutive int variables.
&blah
Type: int**.
Significance: It contains the adress of the pointer of the first element in the array. In other words, it''s a pointer to a pointer targetted at the first element in the array.
Unfortunately, in the second example here, this is poor programming practice. You see, blah is not an L-value. It has no ''defined'' place in memory. Instead, it is an expression which evaluates to a pointer which points to the first lement of blah[80]. To get a pointer to blah using &blah is dangerous. Although the compiler will let you do it, you are in effect, requesting a pointer to a pointer which you have not declared.
You're absolutely right; it was a poor example.
If blah had been a dynamically-allocated array, there would be no problem. The distinction is not static-versus-dynamic but, rather, how they're accessed. A dynamically-allocated array is accessed through a pointer variable (as in int* array_ptr = new int[80] or int* array_ptr = (int*)malloc(80 * sizeof(int))). Since a variable is a valid memory object, you can take the address of that. Of course, I can't imagine very many good reasons for that, especially considering that [accidentally] modifying the pointer will result in a memory leak. A statically-allocated array behaves as a pointer, but is not a pointer variable, and you should only take the address of variables (and functions).
Edited by - merlin9x9 on July 19, 2001 4:02:37 AM
If blah had been a dynamically-allocated array, there would be no problem. The distinction is not static-versus-dynamic but, rather, how they're accessed. A dynamically-allocated array is accessed through a pointer variable (as in int* array_ptr = new int[80] or int* array_ptr = (int*)malloc(80 * sizeof(int))). Since a variable is a valid memory object, you can take the address of that. Of course, I can't imagine very many good reasons for that, especially considering that [accidentally] modifying the pointer will result in a memory leak. A statically-allocated array behaves as a pointer, but is not a pointer variable, and you should only take the address of variables (and functions).
Edited by - merlin9x9 on July 19, 2001 4:02:37 AM
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement