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? :/

rita
  • 101
  • 1
  • 9

1 Answers1

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.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • 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 – rita Sep 28 '14 at 00:08
  • 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). – M.M Sep 28 '14 at 02:10
  • @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 Sep 28 '14 at 09:15
  • @ouah i'm not sure if `(int)atof(......)` is guaranteed to be the same on repeat invocations – M.M Sep 28 '14 at 10:44