我需要创建一个程序,该程序需要一定数量的行和列(来自输入),并创建一个由[行]字符串组成的数组,每个字符串带有[列]个字符(加上空字符'\ 0'), C。所以我做到了:
int R, C;
scanf("%d %d", &R, &C);
int **map = malloc(R * sizeof(*char));
for(int i = 0; i < N; i++) {
map[i] = malloc(C + 1); //+1 for the null character '\0'
}
//Assign a value for each string (i won't write this, i think is desnecessary, but imagine that all the arrays now have a string value
map[2][3] = 'a'; //This causes an error, probably because a string pointer array have constant value, but how can i do the question request?
for(int i = 0; i < N; i++) {
free(map[i]);
}
free(map);
我也尝试过:
int R, C;
scanf("%d %d", &R, &C);
int map[R][C];
//Assign a value for each string
map[2][3] = 'a' //This works, but in other posts i saw that this way of create an array with dynamic size is wrong
那么,执行此操作的最佳方法是什么?在第一次赋值后我可以更改值的动态字符串数组?
C99支持"Variable-Length Arrays,",可让您在运行时声明数组大小。
float read_and_process(int n)
{
float vals[n];
for (int i = 0; i < n; ++i)
vals[i] = read_val();
return process(n, vals);
}
如果您在循环中使用变量R而不是N,则您的第一个代码示例应该可以工作。