我想在C中创建一个2d字符数组,就像在php中一样:
$matrix = array(
array('$','@','*','%','&','#','@','#','#','@'),
array('%','$','@','%','#','%','@','*','&','*'),
array('#','*','&','*','#','@','@','&','%','@'),
array('%','@','*','$','%','&','#','*','@','&'),
array('$','*','&','&','&','@','#','%','*','*'),
array('#','#','@','#','&','%','*','$','#','#'),
array('&','$','$','#','@','#','@','$','%','*'),
array('@','$','$','*','&','$','#','*','#','*'),
array('%','$','*','@','&','@','&','#','#','#'),
array('#','@','%','*','#','&','#','$','%','#')
);
我尝试写这段代码:
int size = 10;
char matrix[size][size] = {
{'$','@','*','%','&','#','@','#','#','@'},
{'%','$','@','%','#','%','@','*','&','*'},
{'#','*','&','*','#','@','@','&','%','@'},
{'%','@','*','$','%','&','#','*','@','&'},
{'$','*','&','&','&','@','#','%','*','*'},
{'#','#','@','#','&','%','*','$','#','#'},
{'&','$','$','#','@','#','@','$','%','*'},
{'@','$','$','*','&','$','#','*','#','*'},
{'%','$','*','@','&','@','&','#','#','#'},
{'#','@','%','*','#','&','#','$','%','#'}
};
我对c很新,所以我真的不知道c中2d数组的概念。但由于某种原因,上面的代码给出了错误。请帮忙。
答案 0 :(得分:3)
这是因为C编译器认为您正在尝试初始化在运行时确定的长度数组,即使您在编译时提供了大小10
。
用int size= 10
替换#define SIZE 10
将解决此问题:
#define SIZE 10
...
char matrix[SIZE][SIZE] = {
{'$','@','*','%','&','#','@','#','#','@'},
{'%','$','@','%','#','%','@','*','&','*'},
{'#','*','&','*','#','@','@','&','%','@'},
{'%','@','*','$','%','&','#','*','@','&'},
{'$','*','&','&','&','@','#','%','*','*'},
{'#','#','@','#','&','%','*','$','#','#'},
{'&','$','$','#','@','#','@','$','%','*'},
{'@','$','$','*','&','$','#','*','#','*'},
{'%','$','*','@','&','@','&','#','#','#'},
{'#','@','%','*','#','&','#','$','%','#'}
};
答案 1 :(得分:2)
因此解决方案是在编译之前提供有关数组大小的计算机信息。所以你可以用宏定义大小
#define size 10
或者使用malloc(以及其他内存分配函数)在堆上动态创建数组
如果初始化数组,则可以省略维。例如
int a[] = {1, 2, 3};
int b[][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
答案 2 :(得分:1)
int size = 10;
char matrix[size][size];
memcpy(&matrix[0][0],
"$@*%&#@##@"
"%$@%#%@*&*"
"#*&*#@@&%@"
"%@*$%&#*@&"
"$*&&&@#%**"
"##@#&%*$##"
"&$$#@#@$%*"
"@$$*&$#*#*"
"%$*@&@&###"
"#@%*#&#$%#", size*size);
答案 3 :(得分:0)
假设一个10x10字符数组:
char **matrix = malloc(sizeof(char*)*10);
int i, len = 10;
for(i = 0; i < len; i++)
matrix[i] = (char *)malloc(11) // the 11th one is for the null '\0' character (you can ignore it if you like)
现在您可以根据需要填充char数组位置:
// for example row 1 column 1
matrix[0][0] = '$';
应该有所帮助。
完成后,请确保使用“free”释放分配的内存。