Vasanth
Vasanth

Reputation: 21

Array of unknown bound usage in C programming

I output of below code is undefined when I ran multiple times. I would like to know why the output is undefined and what will be implication when I try to assign value to an array of unknown bound.

#include <stdio.h>

int main()
{
  int a[]= {};
  int num_of_elements;
  int count = 0;

  printf("Enter the number of elements:\n");
  scanf("%d",&num_of_elements);

  printf("Enter the numbers:\n");
  for(count=0; count<num_of_elements; ++count)
  {
    scanf("%d", &a[count]);
  }
  printf("\n");

  for(count=0; count<num_of_elements; count++)
  {
    printf("%d,   ", a[count]);
  }
  printf("\n");

  return 0;
}

Output when run at different times:

Enter the number of elements:
2

Enter the numbers:
1 2

0,   0,

Enter the number of elements:
3

Enter the numbers:
1 2 3

0,   0,   2,

Enter the number of elements:
4

Enter the numbers:
1 2 3 4

0,   0,   2,   3,
Segmentation fault

Enter the number of elements:
5

Enter the numbers:
1 2 3 4 5

0,   0,   2,   3,   4,
Segmentation fault

Upvotes: 2

Views: 207

Answers (2)

Marievi
Marievi

Reputation: 5001

I would like to know why the output is undefined and what will be implication when I try to assign value to an array of unknown bound

The size of variable a will be 0, as num_of_elements has not been scanf'ed at that point, so you can't store anything in it.

The solution is to declare the array after you have read its size from the user. This means :

#include <stdio.h>

int main()
{
    int num_of_elements;
    int count = 0;

    printf("Enter the number of elements:\n");
    scanf("%d", &num_of_elements);

    //define here your array
    int a[num_of_elements];

    ...

    return 0;
}

Upvotes: 1

user2371524
user2371524

Reputation:

As a first hint, when you try to compile this with gccusing -pedantic, it will refuse to compile:

$ gcc -std=c11 -Wall -Wextra -pedantic -ocrap.exe crap.c
crap.c: In function 'main':
crap.c:5:12: warning: ISO C forbids empty initializer braces [-Wpedantic]
   int a[]= {};
            ^
crap.c:5:7: error: zero or negative size array 'a'
   int a[]= {};
       ^

And indeed, the size of such a variable is 0, so you can't store anything in it.

Still it is a valid syntax and has its uses, for example as a "flexible array member" of a structure:

struct foo
{
    int bar;
    int baz[];
};

[...]

struct foo *myfoo = malloc(sizeof(struct foo) + 5 * sizeof(int));
// myfoo->baz can now hold 5 integers

Upvotes: 1

Related Questions