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;
}
10
  • 1
    Please indent the code- i.e. make it readable Commented Jun 29, 2014 at 19:49
  • 1
    And why are you making life so difficult. You can pass back the result of malloc] Commented Jun 29, 2014 at 19:51
  • In C, *ptr1=(float*)malloc(3*sizeof(float)); - the (float*) cast is redundant. Commented Jun 29, 2014 at 19:52
  • Also, a[b] is equivalent to *(a+b). Commented Jun 29, 2014 at 19:55
  • Also, don't cast the result of malloc. Commented Jun 29, 2014 at 19:59

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Finally understood it!! Thanks a lot.
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]);
}

4 Comments

Programming language can be represented exactly.
@Deduplicator why can't we cast malloc?
@user3748848 , No problem just redundant it simply correct case. But cast it wrong often human error is made​​. Not required even though do it.
Well, it is not a code of enough explanation needed exaggerated. ;D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.