manubmxnsb
manubmxnsb

Reputation: 151

Trying to modify array in function in C

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

void read_array(int *arr) {
  FILE *fp;
  int var;
  int i = 0;
  fp = fopen("array.txt", "r");
  for (i = 0; i < 10; i++) {
    fscanf(fp, "%d", &var);
    arr[i] = var;
  }
  fclose(fp);
}

int main() {
  int array[10];
  int i;
  for (i = 0; i < 10; i++) {
    array[i] = 0;
  }
  read_array(array[10]);
  for (i = 0; i < 10; i++) {
    printf("%d ", array[i]);
  }
  return 0;
}

This is my code. I'm trying to modify the array inside the function, based on a text file i have, that already has 10 numbers(0-9). What do I do wrong here? Thanks for input guys & wish you the best! You the coolest!

Upvotes: 0

Views: 80

Answers (2)

AKX
AKX

Reputation: 169022

You're not telling us what the error or problem is, but I can make an educated guess:

read_array(array[10]);

should be just

read_array(array);

Beyond that, though, read_array() should preferably also take a maximum size argument, because otherwise it has no way of knowing the size of the array. For your program, it does happen to always be 10. Something like this:

/**
Read up to `n` integers from `array.txt` into the array `arr`,
returning the count that was successfully read.
*/
int read_array(int *arr, int n) {
  FILE *fp;
  int var;
  int i;
  fp = fopen("array.txt", "r");
  for (i = 0; i < n; i++) {
    if(fscanf(fp, "%d", &var) < 1) {  // < 1 means EOF or scan failed
      break;
    }
    arr[i] = var;
  }
  fclose(fp);
  return i;
}

Upvotes: 2

David C. Rankin
David C. Rankin

Reputation: 84561

The principle you must understand, that underlies the correct answer from @AKX, is Array / Pointer Conversion. It is covered in the C-Standard as follows:

6.3.2.1 Lvalues, arrays, and function designators

(p3) Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary '&' operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue.

C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3)

(note: the C17 standard removes _Alignof as an exception to the rule)

What this means is that any time you access an array, the array is converted to a pointer to its first element. So where you have:

int array[10];

and your function declaration is:

void read_array(int *arr)

(a function taking a pointer-to int as its parameter)

Then to provide the pointer-to int you need only provide the array name, array, as the argument -- which due to 6.3.2.1(p3) is converted to a pointer to the first element in the array. That is how you pass the array to your function.

Upvotes: 2

Related Questions