0

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;
}
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
G.One
  • 209
  • 4
  • 15

2 Answers2

1

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;
}
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0
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]);
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70