问题描述
我想从一个文件中读取如下:
I wanna read from one file which will be like this:
10
1 7
9 7
1 1
9 1
2 4
8 4
6 5
6 3
4 3
4 5
数字。第一个是N并且告诉我们应该读多少行。
在我阅读之后我必须将它们打印回给用户,这就是问题所在。这是我的代码:
the numbers. The first is the N and tell us how much lines should we read.
After i read them i have to print them back to the user and thats the problem. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int N, simeio[N][N], i, x ,y;
FILE *fp;
fp = fopen("pulsars.in","r");
fscanf(fp,"%d", &N);
for(i=0; i<N; ++i)
{
fscanf(fp,"%d %d", &x, &y);
simeio[x][y] = i;
}
fclose(fp);
for(i=0; i<N; ++i) printf("%d %d", simeio[i][i]);
getchar();
}
问题出在哪里?请尽快回答我。
感谢您的时间。
Where is the problem? Please answer me ASAP.
Thanks for your time.
推荐答案
int * simeio;
(指向int的指针,稍后将充当数组)和在从文件中读取N的值后,使用malloc()分配内存。请查看 []有关malloc()的信息。
其次,根据您的文件pulsars .in,它看起来不像NxN阵列。它看起来像我作为Nx2阵列。因此,您可以将以下代码
(a pointer to int, which will act as an array later) and use malloc() to allocate memory after you have read the value for N from the file. Take a look at www.cplusplus.com/malloc[^] for information on malloc().
Second, according to your file "pulsars.in", it doesn''t look like an NxN array. It looks like to me as an Nx2 array. So you can change the following code
int simeio[N][N]
更改为
int simeio[N][2]
。
第三,您需要更正代码
.
Third, you need to correct the code
simeio[x][y] = i;
如下:
as following:
simeio[i][0] = x;
simeio[i][1] = y;
另外,插入一些printf语句到检查是否正确读取了文件中N,x和y的值。然后你应该没问题。
祝你好运:)
Additionally, insert some printf statements to check whether you read the values for N, x, and y from the file correctly. Then you should be OK.
Good luck :)
这篇关于C中的多维数组问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!