For starters bear in mind that it is not a good style of programming to use uppercase letters for identifiers of variables.
In this statement
A[3][4]={{1,2,3,4},{1,2,3,4},{1,2,3,4}};
you are trying to assign values in the braced list to the scalar object of the type int
that even does not exists because the indices 3
and 4
access memory outside the dynamically allocated arrays.
So as the above expression statement uses the assignment operator then the compiler expects that the right operand of the assignment is an expression. Braced lists are not expressions. So the compiler issues an error.
Pay attention to that arrays do not have the assignment operator. You need to copy elements of one array into another or set elements individually.
You could initially declare an array and initialize it with the braced list like
int A[3][4]={{1,2,3,4},{1,2,3,4},{1,2,3,4}};
As for dynamically allocated arrays then you could initialize their elements in for loops like for example
for ( size_t i = 0; i < 3; i++ )
{
int value = 1;
for ( size_t j = 0; j < 4; j++ )
{
A[i][j] = value++;
}
}
Another approach is to use compound literals like
for ( size_t i = 0; i < 3; i++ )
{
memcpy( A[i], ( int[] ){ 1, 2, 3, 4 }, sizeof( int[4] ) );
}
Here is a demonstration program.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( void )
{
enum { M = 3, N = 4 };
int **a = malloc( sizeof( int *[M] ) );
for ( size_t i = 0; i < M; i++ )
{
a[i] = malloc( sizeof( int[N] ) );
memcpy( a[i], ( int[N] ){ 1, 2, 3, 4 }, sizeof( int[N] ) );
}
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
printf( "%d ", a[i][j] );
}
putchar( '\n' );
}
for ( size_t i = 0; i < M; i++ )
{
free( a[i] );
}
free( a );
}
The program output is
1 2 3 4
1 2 3 4
1 2 3 4
In general you should check whether memory was allocated successfully.