Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring Size of Array Using Variable

Tags:

arrays

c

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

#pragma warning (disable : 4996)

void main() {

    int matrix[30][50];

    int sizeRow, sizeCol;

    printf("Number of Rows in your table    : ");
    scanf("%d", &sizeRow);

    printf("Number of Columns in your table : ");
    scanf("%d", &sizeCol);

    int sum[sizeRow] = { 0 };

    for (int row = 0; row < sizeRow; row++){
        for (int col = 0; col < sizeCol; col++){
            printf("Input element [%d][%d] : ", row, col);
            scanf("%d", &matrix[row][col]);
            sum[row] += matrix[row][col];
        }
    }

    printf("Total of each row:\n");
    for (int row = 0; row < sizeRow; row++){
        printf("ROW[%d] SUM :\t%d\n", row, sum[row]);
    }

    system("pause");
}

I am getting error in the int sum[sizeRow] = { 0 }; where it says that my array should be a constant but the user in my case should determine the array size. Any way I can fix this?

like image 342
ZahirSher Avatar asked Dec 14 '22 21:12

ZahirSher


1 Answers

MSVC doesn't support variable length arrays. You'll need to allocate memory with calloc. Unlike malloc, calloc initializes all bytes to 0:

int *sum = calloc(sizeRow, sizeof(int));

Don't forget to free the memory afterward.

like image 92
dbush Avatar answered Jan 01 '23 11:01

dbush