gpt4 book ai didi

c - 下标值不是数组也不是指针

转载 作者:行者123 更新时间:2023-11-30 15:27:05 24 4
gpt4 key购买 nike

我有一个程序,可以从文件中读取二维数组,并使其成为锯齿状数组(其中每行的大小都完美适合所有非零元素)。然后它打印出数组。

但是我有几个问题无法解决。

具体

26: I get a warning (assignment makes integer from pointer without cast

44: error: subscripted value is neither array not pointer

我可以做什么来修复它?

int main() {

FILE *inputFile1 = fopen("denseMatrix1.txt", "r");

char inputBuffer[SIZE];
int dim1, dim2, input, i, j;
int *mtrx1;

fgets(inputBuffer, SIZE, inputFile1);
sscanf(inputBuffer, "%d%d", &dim1, &dim2);

mtrx1 = malloc(sizeof(int *) * dim1);

for (i=0; i<dim1; i++) {
int cols=0;
int *row = malloc(sizeof(int) * cols);
fgets(inputBuffer, SIZE, inputFile1);
for (j=0; j<dim2; j++) {
sscanf(inputBuffer, "%d", input);
printf("i=%d j=%d input=%d\n", i, j, input); // ADDED LINE (NOT PRINTING)
if (input) {
cols++;
row = realloc(row, sizeof(int) * cols);
row[cols-1] = input;
}
}
mtrx1[i] = row;
cols=0;
}

int mtrx3[DIM1][DIM2] = {0};

// Prints first 2 matrices
printf("First matrix: \n");
printMatrix(mtrx1, dim1);/*

return 0;


// Prints a 2d array matrix
void printMatrix(int *mtrx, int dim1) {
int i, j;
for (i=0; i<dim1; i++) {
for (j=0; j<(sizeof(mtrx[i]) / sizeof(int)); j++) {
printf("%d ", mtrx[i][j]);
}
printf("\n");
}
printf("\n\n");

文件denseMatrix1.txt的内容:

7 8
0 0 0 5 1 0 0 5
0 0 0 0 0 0 0 0
0 0 0 0 1 2 0 0
1 0 0 0 0 0 0 0
3 0 0 5 0 0 3 0
1 0 0 0 0 3 0 0
0 0 0 0 0 0 0 1

最佳答案

代替

int *mtrx1;

使用

int **mtrx1;

使用前一个声明,mtrx[i] 的计算结果为 int。您需要将其计算为 int* 才能使用:

mtrx1[i] = row;

更新

您使用 fgets 获取一行文本并将该文本行与 sscanf 一起使用的策略在 for 中不起作用> 循环。

让我们看一下矩阵的第一行:

0 0 0 5 1 0 0 5

for循环:

for (j=0; j<dim2; j++) {
sscanf(inputBuffer, "%d", input);
printf("i=%d j=%d input=%d\n", i, j, input); // ADDED LINE (NOT PRINTING)
if (input) {
cols++;
row = realloc(row, sizeof(int) * cols);
row[cols-1] = input;
}
}

for 循环中,每次第一行都会将 0 分配给 inputsscanf 不会存储您第一次读取的内容并从剩下的内容继续。

您需要想出不同的策略。例如:

for (i=0; i<dim1; i++) {
int cols=0;
int *row = malloc(sizeof(int) * cols);
fgets(inputBuffer, SIZE, inputFile1);
char* token = strtok(inputBuffer, " \n");
for (j=0; j<dim2; j++) {
input = atoi(token);
printf("i=%d j=%d input=%d\n", i, j, input);
if (input) {
cols++;
row = realloc(row, sizeof(int) * cols);
row[cols-1] = input;
}
token = strtok(NULL, " \n");
}
mtrx1[i] = row;
cols=0;
}

关于c - 下标值不是数组也不是指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27198654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com