本帖最后由 永恒的蓝色梦想 于 2020-7-26 21:20 编辑
微软系的都不支持变长数组,而且你的程序可能下标越界。改为:#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
int main()
{
int citysum, roadsum;
int a, b, c;
scanf("%d %d", &citysum, &roadsum);
int** map = (int**)malloc(citysum * citysum * sizeof(int));
for (int i = 0; i < citysum; i++)
for (int j = 0; j < citysum; j++)
map[i][j] = 0;
for (int i = 0; i < roadsum; i++) {
scanf("%d %d %d", &a, &b, &c);
map[a][b] = c;
}
for (int i = 0; i < citysum; i++) {
for (int j = 0; j < citysum; j++)
printf("%d\t", map[i][j]);
printf("\n");
}
return 0;
}
就可以了。
优化版:#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
int main()
{
int citysum, roadsum;
int a, b, c;
scanf("%d%d", &citysum, &roadsum);
int** map = (int**)malloc(citysum * citysum * sizeof(int));
memset(map, 0, citysum * citysum * sizeof(int));
for (int i = 0; i < roadsum; i++) {
scanf("%d%d%d", &a, &b, &c);
map[a][b] = c;
}
for (int i = 0; i < citysum; i++) {
for (int j = 0; j < citysum; j++) {
printf("%d\t", map[i][j]);
}
putchar('\n');
}
return 0;
}
还可以使用 calloc:#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
int main()
{
int citysum, roadsum;
int a, b, c;
scanf("%d%d", &citysum, &roadsum);
int** map = (int**)calloc(citysum * citysum, sizeof(int));
for (int i = 0; i < roadsum; i++) {
scanf("%d%d%d", &a, &b, &c);
map[a][b] = c;
}
for (int i = 0; i < citysum; i++) {
for (int j = 0; j < citysum; j++) {
printf("%d\t", map[i][j]);
}
putchar('\n');
}
return 0;
}
|