简体   繁体   English

试图扫描到二维分配数组c编程

[英]trying to scan in to a 2-d malloc'd array c programming

i've looked through quite a few questions of 2-d malloc'd arrays already but bascially for whatever reason i cannot find a solution.... my google fu sux sorry =(. been using the site all day for syntactual help though thanks to everyone who helps here! =) 我已经看过相当多的2-d malloc'd数组问题,但无论出于何种原因我都无法找到解决方法。...我的google sux抱歉=(。虽然整天都在使用该网站进行句法帮助感谢所有在这里提供帮助的人!=)

anyways i cant seem to get this fscanf to work =/ if someone could help me it would be much appreciated because i cant see any error at all but i know there is one because it is at this point that my program crashes. 无论如何,我似乎无法使此fscanf正常工作= /如果有人可以帮助我,将不胜感激,因为我根本看不到任何错误,但我知道有一个错误,因为这是我的程序崩溃的原因。

    array1 = (int**)malloc((c)*sizeof(int*));
        int a = 0, i = 0;
        for (a = 0; a < c; a++){
            array1[a] = (int*)malloc((c+1)*sizeof(int));

        }
    a=0;

    for(a = 0; a < c; a++){
                for(i = 0; i < c; i++){
                fscanf(ifp, "%d", array1[a][i]);

    }
    }

where c is the maximum size of the array needed. 其中c是所需数组的最大大小。 in this case it is set to 3 but i do need it as a variable 在这种情况下,它设置为3,但我确实需要将其作为变量

When using the scanf family of function to read a value, the destination needs to be a pointer. 使用scanf系列函数读取值时,目标必须是指针。 array1[a][i] is not a pointer, it an actual value (which scanf will treat as a pointer and you now entered the territory of undefined behavior ). array1[a][i] 不是指针,而是一个实际值( scanf将其视为指针,并且您现在输入了undefined behavior的区域 )。

What you want is &array1[a][i] . 您想要的是&array1[a][i]

PS. PS。 You should not cast the returned value of malloc . 您不应该转换malloc的返回值。

fscanf takes pointers, so I would think you need to prepend its third argument with an ampersand. fscanf使用指针,因此我认为您需要在其第三个参数前加上“&”号。 Didn't the compiler warn you about that? 编译器没有警告您吗?

You want: 你要:

fscanf(ifp, "%d", &array1[a][i]);
                  ^

malloc and other syntext is correct, the issue is in reading the value to array malloc和其他文本正确,问题在于读取数组的值

replace this fscanf(ifp, "%d", array1[a][i]); 替换此fscanf(ifp, "%d", array1[a][i]);

with

fscanf(ifp, "%d", &array1[a][i]);

Always enable complier warning, and pay heed to it:) 始终启用编译器警告,并留意该警告:)

You need to read this. 您需要阅读。

Please develop habit of reading manpages. 请养成阅读手册的习惯。 It helps a lot. 这很有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM