1

Basically, I am attempting to write a simple C function that prompts the user for an array length, and then asks the user to input values (ints) for the array.

Sample Output Desired:

Enter Array Length: 5
Enter values for the array:
1 2 3 6 7

The current array is:
1 2 3 6 7

Here is my code at the moment. I feel as if this is should work, but with such a basic knowledge of C, it's causing a segmentation fault.

int intersect()
{
  int size, index, input;
  printf("Enter the size of the arrays:\n");
  scanf("%d", &size);

  int arr1[size], arr2[size];
  index = 0;
  printf("Enter the elements of the first array:\n");
  while (index < sizeof(arr1))
    {
      scanf("%d ", &input);
      arr1[index] = input;
      index = index + 1;
    }

  printf("The current array is:\n %d", arr1);
}

I don't understand how to collect input for an array that is of length that a user defines. Any explanation is appreciated!

Micah
  • 263
  • 1
  • 5
  • 14
  • You have an index-out-of bound problem, Correct `while (index < sizeof(arr1)/sizeof(arr1[0]))` additionally `printf("The current array is:\n %d", arr1);` is wrong, you need a loop to print array elements as: `printf("The current array is:\n %d", arr[i]);` in loop that updated `i`. – Grijesh Chauhan Sep 23 '13 at 03:00
  • Read: [Weird behavior when printing array in C?](http://stackoverflow.com/questions/18009725/weird-behavior-when-printing-array-in-c/18009736#18009736) – Grijesh Chauhan Sep 23 '13 at 03:00

1 Answers1

6

sizeof returns the memory occupied in bytes and not the array length. So basically you are checking if index is less than 40 (size of Integer * array length). Since the array does not have space to store 40 integer values, it is giving Undefined behaviour ( some time segmentation fault).

You should instead change

while (index < sizeof(arr1))

to

while (index < size)

Second also correct:

printf("The current array is:\n %d", arr1);
//                               ^    ^  address             

as

for (i = 0; i < size, i++)  
  printf("The current array is:\n %d", arr1[i]);

either to print address use %p.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
hrv
  • 925
  • 6
  • 13
  • Thank you! I changed it to while (index <= (size - 1)) – Micah Sep 23 '13 at 03:05
  • @Micah You should also update the printf statement for printing values of the array as Grijesh mentioned, otherwise it will only print the address of the first element of the array – hrv Sep 23 '13 at 03:12
  • 2
    @hrv I don't wanted to write similar (I linked) answer again and again so updated yours hope you like it :) – Grijesh Chauhan Sep 23 '13 at 03:15