1

first of all I looked other titles about segmentation faut 11 error.

This one is very close to me. But cannot solve my problem. How to fix segmentation fault 11 error

This code take 2 array from user with readArray function Here is the code

int *readArray(int p[]) {
  int i = 0;
  printf("Enter the array :\n");
  for (i = 0; i <= 10; i++) {
    printf("a%d : ", i);
    scanf("%d", &p[i]);
  }
  return p;
}

int main() {

  int *firstArray;
  int *secondArray;
  int *resultArray;

  firstArray = readArray(firstArray);
  // printArray(firstArray);

  secondArray = readArray(secondArray);
  // printArray(secondArray);

  // addArray(firstArray,secondArray,resultArray);
  // printArray(resultArray);
  printf("\n");
  return 0;
}

I can take first one from user but cannot take second. It gets error segmentation fault 11.

How can I solve it?

Thank you all! FIXED CODE

 void readArray(int p[]) {
  int i = 0;
  printf("Enter the array :\n");
  for (i = 0; i < 11; i++) {
    printf("a%d : ", i);
    scanf("%d", &p[i]);
  }

}

int main() {

  int firstArray[11];
  int secondArray[11];
  int resultArray[11];

  readArray(firstArray);
  // printArray(firstArray);

  readArray(secondArray);
  // printArray(secondArray);

  // addArray(firstArray,secondArray,resultArray);
  // printArray(resultArray);
  printf("\n");
  return 0;
}

1 Answers1

1

Your firstArray, secondArray, and resultArray pointers are all uninitialized, so attempting to access p[i] in readArray() is undefined.

Instead of:

int * firstArray;
int * secondArray;
int * resultArray;

You can use:

int firstArray[11];
int secondArray[11];
int resultArray[11];

If you really want to dynamically allocate the memory, then you'd have to use malloc() instead:

int * firstArray = malloc(sizeof(int) * 11);
int * secondArray = malloc(sizeof(int) * 11);
int * resultArray = malloc(sizeof(int) * 11);

And delete them after you're done using them:

free(firstArray);
free(secondArray);
free(resultArray);

By the way, since you're passing in an array (or pointer) to readArray() and modifying its contents, you don't need to return anything. It's sufficient to define void readArray(int p[]) {...} (or void readArray(int * p) {...} if you're using pointers).

frslm
  • 2,969
  • 3
  • 13
  • 26
  • 1
    @mehmetsalihbindak aside: please try to avoid using magic numbers. The array length is 11 but you use 10 in the loop `for (i = 0; i <= 10; i++)`. This makes the code harder to follow and maintain. Use a `const int` or a `#define` for the array length and drive everything from that. So (assuming 11 will be defined) the loop should be `for (i = 0; i < 11; i++)`. – Weather Vane Nov 23 '17 at 21:36