#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