hey Salem, thanks for the answer...
> int* ptr = (int*)malloc(32 * sizeof(char));
You need sizeof int (you're allocating int's), not sizeof(char).
that seems to be a relic from when I was using char and trying to assign letters... missed that in the re-type
More robustly, one would write
int *ptr = malloc( 32 * sizeof(*ptr) );
So why is there no standard way of writing the pointer symbol? Writing it like this is really confusing and makes me think of is as a unary operator, even though this is clearly a declaration and it's being used as a type. Could I write:
Code:
int* ptr = malloc( 32 * sizeof(ptr) );
Or do I need to put a unary * inside the sizeof parameter? Both seem to compile just fine, would there be anything hidden happening here that I can't see at compile time?
printf("%c", *returnedptr);
Revise your printf formats.
%c is for chars
%d is for ints
Definitely, this is another artefact. Sorry!
So perhaps
printf("%d ", returnedptr[i] );
Yeh I thought of that as well, when I try to iterate with [i] all I get is a continuous output of zero.
I have had some success with the following solution:
Code:
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
int* returnptr(){
int* ptr = (int*)malloc(32 * sizeof(int));
return ptr;
}
int main(int argc, char** argv) {
int* returnedptr = returnptr();
for (uint i = 0; i<32; i++){
//returnedptr[i] = i;
printf("%d \n", returnedptr);
}
return (EXIT_SUCCESS);
}
This prints out the first address, but no iteration.
Again if I try to use:
Code:
for (uint i = 0; i<32; i++){
//returnedptr[i] = i;
printf("%d \n", returnedptr[i]);
}
It simply prints out zeros.