-1

Are there any limitations when implementing scanf int data type to an array in C? The code below gives me a "segmentation fault(core dumped) when array has more than 6 indices.

====example code=========

#include <stdio.h>

int main(void)
{    
    int size;
    int array[size];
    int x;

    scanf("%d", &size);

    for(x = 0; x < size; x++){
        scanf("%d", &array[x]);
    }
    for(x = 0; x < size; x++){
        printf("[%d] ", array[x]);
    }
 }


input:
4
3 45 5 76
output:
[3] [45] [5] [76]

input:
7
34 2 5 6 9 3 8
output:
Segmentation fault(core dumped)

My goal is to have a dynamic array. The user will decide its size. So far this proves impossible. I understand the dynamic array approach can be implemented with struct or c++ vector. However, I would like to understand whether the error is due to the code structure or am I ignorant of certain limitation in the C array.

I look forward to your knowledgeable input.

Mi-Creativity
  • 9,554
  • 10
  • 38
  • 47
  • 1
    you array as size 0, because the size is 0 at compile time. To change de size of the array at run time you have to allocate memory for the array using malloc. Don't forget to free memory at the end – MiguelSlv Feb 26 '16 at 14:53
  • At the time you declare `array[size]`, `size` is uninitialized. Changing `size` afterwards is too late! – mah Feb 26 '16 at 14:57
  • ...and whether `size` is initialized **after** the `scanf()` is unclear, since **you did not check the return value**. If the user entered letters instead of digits, `scanf( "%d", &size )` will fail, leaving `size` uninitialized (and all subsequent `scanf( "%d", ... )` will fail as well as the letters are still sitting in `stdin`, unread). – DevSolar Feb 26 '16 at 14:58
  • 1. Your `size` is a random number off the stack, thus your `array[size]` is of an unknown size at runtime. 2. You don't `malloc()` any memory to ensure it has enough memory to fit there, and be a dynamic array. 3. Use a hardcoded known value, such as `array[128]` instead of `array[size]` until you switch to using a dynamicly-allocated array. – Shark Feb 26 '16 at 15:04

5 Answers5

0
 int size;
 int array[size];

size is uninitialized right now . Array of what size would be created ?

Declare array after scanf("%d",&size).

ameyCU
  • 16,489
  • 2
  • 26
  • 41
0

You can not use array[size] when size is not defined yet ! Instead if you want to use a dynamic array, you can do it like this:

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

void main()
{    
  int size;
  int *array;
  int x;

  if (scanf("%d", &size)==1){
  array=calloc(size*sizeof(int));
  }
  //check if allocation has been done      

  for(x = 0; x < size; x++){
    scanf("%d", &array[x]);
  }
  for(x = 0; x < size; x++){
    printf("[%d] ", array[x]);
  }

  free(array);
  return;
}
ReshaD
  • 936
  • 2
  • 18
  • 30
0

The "classic" way would be to allocate memory for your array, either using malloc(size * sizeof(int)) or by using calloc(size, sizeof(int)). The former makes no guarantees as to the state of the memory allocated (apart from "allocated"), the latter guarantees that the memory has been zeroed before the function returns.

Vatine
  • 20,782
  • 4
  • 54
  • 70
  • 1
    For people that don't yet understand why the array size is failing in this case, advising them to use malloc is really doing them a disservice. – mah Feb 26 '16 at 16:54
0

I am going to point out 2 things

  1. Write int array[size]; after scanf statement and include stdlib.h in your code. In the new versions of gcc compiler takes care of memory allocation and finally freeing it for you. Also return some value as your return type is int.

  2. But my advise to you is that use malloc statement in the following fashion as you might need to run the code on older version of gcc. And also compiler internally does the same thing.

        #include <stdio.h>
        #include <stdlib.h>
        int main(void)
        {    
            int size;
            scanf("%d", &size);
            int *array;
            array=malloc(size*sizeof(int));
            int x;
    
            for(x = 0; x < size; x++){
                scanf("%d", &array[x]);
            }
            for(x = 0; x < size; x++){
                printf("[%d] ", array[x]);
            }
      free (array);
      return 0;
    
     }
    
Kevin Pandya
  • 1,036
  • 1
  • 9
  • 12
  • don't use cast in allocation. – ReshaD Feb 26 '16 at 15:10
  • Why? What's the problem? – Kevin Pandya Feb 26 '16 at 15:12
  • 1
    [Don't cast malloc() return value](http://stackoverflow.com/questions/605845) in C. (*Do* cast in C++.) **DO** check `scanf()` return value, always. – DevSolar Feb 26 '16 at 15:13
  • For people that don't yet understand why the array size is failing in this case, advising them to use malloc is really doing them a disservice. That said, if you're going to provide an example using `malloc`, don't you think the call to `malloc` should actually be somewhere in the code you provide? Bravo on at least including the `free()` but currently `array` is not properly initialized. – mah Feb 26 '16 at 16:56
  • Thanks Kevin and everyone else. I also realize the importance of `free()` in freeing memory to prevent buffer overflow issues. – Robens Loft Feb 27 '16 at 08:55
0

Better you dynamically allocate memory for taking a user input size.

int *arr,size;
scanf("%d",size);
arr=(int *)malloc(sizeof(int)*size);

This will create an integer array of length "size".

Aniket Bhanja
  • 76
  • 1
  • 2
  • For people that don't yet understand why the array size is failing in this case, advising them to use malloc is really doing them a disservice. – mah Feb 26 '16 at 16:54