Declaring array size using a variable

#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 get an error in int sum[sizeRow] = { 0 };where it says that my array should be constant, but the user in my case should determine the size of the array. How can i fix this?

+4
source share
4 answers

MSVC does not support variable length arrays. You must allocate memory with calloc. Unlike malloc, callocinitializes all bytes to 0:

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

Do not forget the freememory after.

+6
source

, MSVC. VLA. Visual Studio 2015, C99, - C99 (, C99). , . , , , , .

, C99 (VLA) firstprivate ( 2.7.2.2 . 26). : MS

void f(int m, int C[m][m])  
{  
    double v1[m];  
    ...  
    #pragma omp parallel firstprivate(C, v1)  
    ...  
}  

, "" , , GCC Clang, -std=c99 -std=c11 . GCC C, .

malloc, . , .

+4

int sum[sizeRow] , C99, MSVC VLA.
, VLA , ,

int sum[sizeRow] = { 0 };

, , VLA.

§6.7.9- (3):

, .

memset

int sum[sizeRow];  
memset(sum, 0, sizeof(sum));  

a for

for(int i = 0; i < sizeRow; i++)
    sum[i] = 0;
+2

You must include the #define directive to set the rows and columns of the array, and then force the user to enter them, for example:

#define ROWCOL
#define COLUMNCOL
0
source

Source: https://habr.com/ru/post/1684008/


All Articles