Home > other >  Error in User defined size for array in c
Error in User defined size for array in c

Time:07-17

*I am taking the size of array from user, the program runs perfectly when i declare int arr[n]; below the scanf in main but, it when i run following code is behaves differently each time, sometimes take more values, some times shows bus error. Even the value of n changes sometimes. *

//Code

#include <stdio.h>

void read_array(int arr[], int *n);
void print_array(int arr[], int *n);

int main() {
    int n;

    int arr[] = {};

    printf("Enter array length ");
    scanf("%d", &n);
    printf("\nmain elements %d", n);

    read_array(arr, &n);

    printf("\nElements main %d", n);
    print_array(arr, &n);

    return 0;
}

void read_array(int arr[], int *n) {
    int i;

    printf("\n Elements R_A %d", *n);
    printf("\nEnter elements");

    for (i = 0; i < *n; i  ) scanf("%d", &arr[i]);
}

void print_array(int arr[], int *n) {
    int i;

    printf("\n");

    for (i = 0; i < *n; i  ) printf("%d ", arr[i]);

    printf("\n Elements P_A %d", *n);
}

CodePudding user response:

When an array is declared without an explicit size, it size is taken to be the number of elements it is initialized with. So This:

int arr[]={}; 

Declares an array of size 0 which is invalid, and attempting to use it triggers undefined behavior.

CodePudding user response:

int arr[] = {}; is a zero-length array (not supported by the standard) and you access it out of bounds.

If your compiler supports VLAs (variable length arrays), you could use one of those instead.

Example:

#include <stdio.h>

void read_array(int arr[], int *n);
void print_array(int arr[], int n); // no need to send in a pointer to n

int main() {
    int n;

    printf("Enter array length ");
    if (scanf("%d", &n) != 1 || n < 1) return 1; // check that scanf succeeded
    printf("\nmain elements %d", n);

    int arr[n];                                  // a VLA of n elements

    read_array(arr, &n);

    printf("\nElements main %d", n);
    print_array(arr, n);

    return 0;
}

void read_array(int arr[], int *n) {
    printf("\n Elements R_A %d", *n);
    printf("\nEnter elements");

    int i;
    for (i = 0; i < *n; i  ) {
        if (scanf("%d", &arr[i]) != 1) break; // check that scanf succeeded
    }
    *n = i;               // store the number of elements successfully read
}

void print_array(int arr[], int n) {
    int i;

    printf("\n");

    for (i = 0; i < n; i  ) printf("%d ", arr[i]);

    printf("\n Elements P_A %d", n);
}
  • Related