pointer to array of nums delivers no data to the function

Viewed 349

Hey the idea of the code is to scan an array of floats and then create another function that prints that array from the back to the start. For some reason it prints zeros only. Why does it still refer to the part where I set the array to 0? -- float* arr = { 0 };

void ScansFloat(float* arr, int size);
void PrintsFloat(float* arr, int size);

int main()
{
    float* arr = { 0 };
    ScansFloat(arr, 5);
    PrintsFloat(arr, 5);
}

void ScansFloat(float* arr, int size)
{
    int save;
    arr = (int*)malloc(size * sizeof(int));
    for (int i = 0; i < size; i++)
    {
        printf("Enter number in position %d\n", i+1);
        scanf("%f", arr + i);
    }
}

void PrintsFloat(float* arr, int size)
{
    for (int i = size; i >= 0; i--)
    {
        printf("Number %d is %f\n", size - i +1, arr + i);
    }
}
1 Answers

Pass the address of the pointer.

The below code does not change the calling code's pointer.

void ScansFloat(float* arr, int size) {
    ...
    // Here the prior value of `arr` is lost.
    arr = (int*)malloc(size * sizeof(int));  // Wrong type
    for (int i = 0; i < size; i++) {
      ...
      scanf("%f", arr + i);
    }
}

Instead pass the address of the pointer. Also size to the referenced object, not the type. It avoids coding mistakes.

void ScansFloatAlternate(float** arr, int size) {  // **, not *
    ...
    // *arr = (int*)malloc(size * sizeof(int));
    *arr = malloc(sizeof **arr * size);
    if (*arr == 0) Handle_OutOfMemeory();
    for (int i = 0; i < size; i++) {
      ...
      scanf("%f", (*arr) + i);
    }
}

float* arr = 0; // or NULL
ScansFloatAlternate(&arr, 5);

Note: other general improvements possible.


Perhaps a different approach: return the allocated pointer. Various improvements applied.

// Return NULL on error
// Use size_t for sizing
float* ScansFloat(size_t n) {
  float *arr = malloc(sizeof *arr * n);
  if (arr) {
    for (size_t i = 0; i < n; i++) {
      printf("Enter number in position %zu\n", i + 1);
      if (scanf("%f", &arr[i]) != 1) {
        // Invalid input, so consume to the end of the line.
        int ch;
        while ((ch = getchar()) != '\n' && ch != EOF) {
          continue;
        }
        free(arr);
        return NULL;
      }
    }
  }
  return arr;
}

Usage

// float* arr = { 0 };
// ScansFloat(arr, 5);
size_t n = 5;
float* arr = ScansFloat(n);
if (arr == NULL) Fail();
...
free(arr); // free when done
Related