0

Playing with array passing in c. Defining array in function Get_Present_Location() and passing it as a pointer into main where i simply print it. It seems to work except for the last element. Instead of -7 i get 0. Probably there is a stupid mistake on my part but I cannot understand why.

#include <stdio.h>
#include <stdlib.h>

double *Get_Present_Location();

int main(){

    double *Present_Point;
    Present_Point=Get_Present_Location();

    for (int i=0;i<6;i++)
    {
        printf("Joint[%d] = %f\n",i+1,Present_Point[i]);
    }

    return 0;
}

double *Get_Present_Location()  
{

    double point[6]={4,1,5,-3,5,-7};   //Temporary

    return &point;
}

2 Answers 2

3

You have answered your own question.

i.e.

  double point[6]={4,1,5,-3,5,-7};   //Temporary

It is temporary (also the code does not compile with the warnings on)

Sign up to request clarification or add additional context in comments.

Comments

0

In C once you have invalid pointers all manner of mysterious things may happen. You have two problems here. First

return &point;

this is returning a double**, a pointer to a pointer, you should instead

return point;

The array itself is effectively a pointer to double.

More important, as you have noted you are returning a pointer to a temporary, or local, piece of storage. On return from the function this memory, which is probably on the stack, is open to reuse, probably in the next function call. You are returning a pointer to some stack location that is subject to arbitrary change, in effect garbage.

You should instead allocate some memory and return a pointer to that.

Comments

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.