Reputation: 209
I have read a lot of questions of stackoverflow, but couldn't find any solutions on how to deal with this problem of allocating and manipulating pointers inside functions: Can anybody please tell me what's wrong with this code? (I want to allocate and assign values to *D through pointerpass and print the same through pointerprint)
#include<stdio.h>
#include<stdlib.h>
float *D;
void pointerpass(float **ptr1)
{
*ptr1=(float*)malloc(3*sizeof(float));
*(ptr1+0)=1.33;
*(ptr1+1)=2.33;
*(ptr1+2)=3.33;
}
void pointerprint(float **ptr2)
{
int j=0;
for (j=0;j<3;j++)
printf("\n%f\n",*(ptr2+j));
}
int main()
{
pointerpass(&D);
pointerprint(&D);
return 0;
}
Upvotes: 0
Views: 67
Reputation: 59987
Here we go
#include<stdio.h>
#include<stdlib.h>
float * pointerpass(){
float *ret = malloc(3*sizeof(float));
ret[0] = 1.33f;
ret[1] = 2.33f;
ret[2] = 3.33f;
return ret;
}
void pointerprint(float *array) {
int j=0;
for (j=0;j<3;j++) {
printf("\n%f\n",array[j]);
}
}
int main() {
float *x = pointerpass();
pointerprint(x);
free(x); // We do not like memory leaks
return 0;
}
Upvotes: 1
Reputation: 40145
void pointerpass(float **ptr1){
*ptr1=(float*)malloc(3*sizeof(float));
(*ptr1)[0]=1.33;
(*ptr1)[1]=2.33;
(*ptr1)[2]=3.33;
}
void pointerprint(float **ptr2){
int j=0;
for (j=0;j<3;j++)
printf("\n%f\n", (*ptr2)[j]);
}
Upvotes: 0