#include <stdio.h>
#include <stdlib.h>
int main(void){
int n, i, j;
printf("Enter the number of rows and columns: ");
scanf("%d", &n);
int **matrix = malloc(n * sizeof(int *));
for(i = 0; i < n; i++)
matrix[i] = malloc(n * sizeof(int *));
// Read the matrix
for(i=0; i<n; i++)
for(j=0; j<n; j++){
printf("matrix[%d][%d]= ",i+1,j+1);
scanf("%d",&matrix[i][j]);
}
// Print the matrix
for(i = 0; i < n; i++){
printf("%\n");
for(j = 0; j < n; j++)
printf("%d", matrix[i][j]);
}
// Free the allocated memory
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
free((void *)matrix[i]);
free(matrix);
// Just checking if the memory has been freed
for(i = 0; i < n; i++){
printf("%\n");
for(j = 0; j < n; j++)
printf("%d ", matrix[i][j]);
}
system("PAUSE");
return 0;
}
我只是试图动态分配矩阵。尽管在CodeBlocks中一切正常,但是由于我们在大学使用Visual Studio,所以我决定在VS 2010中测试代码。令我惊讶的是我有这么多错误,并且代码无法编译。
我想知道如何解决该问题,以便VS可以很好地编译代码。
这是错误者:
(10): error C2143: syntax error : missing ';' before 'type'
(13): error C2065: 'matrix' : undeclared identifier
(13): error C2109: subscript requires array or pointer type
(19): error C2065: 'matrix' : undeclared identifier
(19): error C2109: subscript requires array or pointer type
(26): error C2065: 'matrix' : undeclared identifier
(26): error C2109: subscript requires array or pointer type
(33): error C2065: 'matrix' : undeclared identifier
(33): error C2109: subscript requires array or pointer type
(33): error C2198: 'free' : too few arguments for call
(35): error C2065: 'matrix' : undeclared identifier
(35): warning C4022: 'free' : pointer mismatch for actual parameter 1
(41): error C2065: 'matrix' : undeclared identifier
(41): error C2109: subscript requires array or pointer type
最佳答案
for(i = 0; i < n; i++)
matrix[i] = malloc(n * sizeof(int *));
更改为
for(i = 0; i < n; i++)
matrix[i] = malloc(n * sizeof(int));
-
// Read the matrix
for(i=0; i<n; i++)
for(j=0; j<n; j++){
printf("matrix[%d][%d]= ",i+1,j+1);
scanf("%d",&matrix[i][j]);
}
也更改为
// Read the matrix
for(i=0; i<n; i++)
for(j=0; j<n; j++){
printf("matrix[%d][%d]= ",i+1,j+1);
scanf("%d",&matrix[i][j]);
}
-
// Free the allocated memory
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
free((void *)matrix[i]);
free(matrix);
也更改为
// Free the allocated memory
for(i = 0; i < n; i++){
free((void *)matrix[i]);
matrix[i] = NULL;
}
free(matrix);
-
// Just checking if the memory has been freed
for(i = 0; i < n; i++){
printf("%\n");
for(j = 0; j < n; j++)
printf("%d ", matrix[i][j]);
}
以上是完全错误的
关于c - Visual Studio动态分配多维数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17395230/