A
Adam Baker
I'm sure this is a fairly basic question. I want a pointer in main()
to be passed to a function, and to allocate memory for the pointer in
the function, and then have it available to main after.
This does not work:
#include <stdio.h>
void func(float *a)
{
a = malloc(5*sizeof(float));
*(a+5) = 15.0f;
}
int main()
{
float *ptr;
func(ptr);
printf("%g\n",*(ptr+5)); // prints something other than 15
return 0;
}
This sort of makes sense, since I'm passing ptr as an argument. Is
there a way to pass ptr so that it behaves as expected? Or do I have
to do this?
#include <stdio.h>
float* func()
{
float *a = malloc(5*sizeof(float));
*(a+5) = 15.0f;
return a;
}
int main()
{
float *ptr;
ptr = func();
printf("%g\n",*(ptr+5));
return 0;
}
Thanks,
Adam
to be passed to a function, and to allocate memory for the pointer in
the function, and then have it available to main after.
This does not work:
#include <stdio.h>
void func(float *a)
{
a = malloc(5*sizeof(float));
*(a+5) = 15.0f;
}
int main()
{
float *ptr;
func(ptr);
printf("%g\n",*(ptr+5)); // prints something other than 15
return 0;
}
This sort of makes sense, since I'm passing ptr as an argument. Is
there a way to pass ptr so that it behaves as expected? Or do I have
to do this?
#include <stdio.h>
float* func()
{
float *a = malloc(5*sizeof(float));
*(a+5) = 15.0f;
return a;
}
int main()
{
float *ptr;
ptr = func();
printf("%g\n",*(ptr+5));
return 0;
}
Thanks,
Adam