0

i am trying to return an array from this code, so that i can later create an array of arrays, in another method i'm writing...

int getValues(char *userInputPtr) {

    int i = 1;
    float fp = 0;
    float num = atof(userInputPtr);


    float *arrayOfFloats = (float *)malloc(sizeof(float) * num);

    for ( i ; i <= num ; i++ ) {
        scanf(" %f", &fp);
        arrayOfFloats[i] = fp;
        printf(" %f", arrayOfFloats[i]);

    }
    printf("\n");

    return arrayOfFloats;

 }

i keep getting the error: warning: return makes integer from pointer without a cast. i just want to return the array! what gives? :/

4
  • It is float * getValues(char *userInputPtr) Commented Sep 27, 2014 at 23:51
  • @rita: Please don't vandalize your question by deleting 90% of the content once it's been answered. Commented Sep 28, 2014 at 1:14
  • How to return an array in C Commented Sep 28, 2014 at 2:09
  • You are accessing beyond the bounds of this array; the loop should be for (int i = 0; i < num; i++) Commented Sep 28, 2014 at 2:09

1 Answer 1

1

Change the return type of your function from int to the correct type you are returning, i. e., change:

int getValues(char *userInputPtr)

to

float *getValues(char *userInputPtr)

Of course, this will not technically return an array (C does not allow arrays to be returned), but a pointer to the first element of the C array.

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

4 Comments

thank you! so, I'm calling this method in main in this way: float array = *getFloatingPointValues(ptrToFPVals); in the process, upon trying to print the values, I'm getting all 0s... I'm not sure what I'm misunderstanding here
With this solution there is no way for the caller to find the length of the array. To do that you will need to either "return" the array length via a pointer parameter, or return a struct. (Actually a better design would be to have a separate function for finding the length; and then this function takes the length as parameter).
@MattMcNabb Of course there is a way for the caller to know the length of the array, the length is n = atof(userInputPtr). Now, if I was asked for a better design, I would have moved the malloc call outside the function and declared the array and its length as the only parameters of the getValues function.
@ouah i'm not sure if (int)atof(......) is guaranteed to be the same on repeat invocations

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.