I am encountering this message "expression must have a constant

ghz 8months ago ⋅ 93 views

I am encountering this message "expression must have a constant value"This was my class assignment and it's running fine but I encounter this message

expression must have a constant value

I am using VS Code. How can I correct it?

#include <stdio.h>
int main()
{

    int n, m;
    printf("Enter the no.of rows ");
    scanf(" %d", &n);
    printf("Enter the no.of columns ");
    scanf(" %d", &m);

    int arr[n][m];

    printf("Enter the elements of the matrix\n");
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            printf("Enter element a[%d][%d] ", i, j);
            scanf("%d", &arr[i][j]);
        }
    }
    printf("The matrix is\n");
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            printf("%d\t", arr[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Code on VScode

Answers

The error message "expression must have a constant value" typically occurs when you try to define an array with non-constant dimensions. In standard C, array dimensions must be constant expressions known at compile time.

In your code, you're trying to define a 2D array arr with dimensions n and m, which are input from the user and thus not constant expressions known at compile time. This is why you're encountering the error.

To fix this issue, you can dynamically allocate memory for the 2D array using pointers instead of defining it as a fixed-size array. Here's how you can modify your code:

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

int main()
{
    int n, m;
    printf("Enter the no. of rows: ");
    scanf("%d", &n);
    printf("Enter the no. of columns: ");
    scanf("%d", &m);

    // Dynamically allocate memory for the 2D array
    int **arr = (int **)malloc(n * sizeof(int *));
    for (int i = 0; i < n; i++)
    {
        arr[i] = (int *)malloc(m * sizeof(int));
    }

    printf("Enter the elements of the matrix\n");
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            printf("Enter element a[%d][%d]: ", i, j);
            scanf("%d", &arr[i][j]);
        }
    }

    printf("The matrix is\n");
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            printf("%d\t", arr[i][j]);
        }
        printf("\n");
    }

    // Free dynamically allocated memory
    for (int i = 0; i < n; i++)
    {
        free(arr[i]);
    }
    free(arr);

    return 0;
}

In this modified version, we're using pointers to dynamically allocate memory for the 2D array based on user input for the number of rows (n) and columns (m). This allows you to create arrays with sizes determined at runtime, resolving the error you encountered. Additionally, don't forget to free the dynamically allocated memory at the end of the program to prevent memory leaks.