我正在使用C.我遇到了使用fscanf函数指针的问题.当我尝试做的时候:
int *x;
/* ... */
fscanf(file, "%d", x[i]);
Run Code Online (Sandbox Code Playgroud)
我的编译器给了我一个警告说"格式参数不是一个指针",代码就没有运行(我得到一条消息说"Water.exe已经停止工作").如果我用*替换x,它只是不编译...这只是一个语法问题?
Chr*_*utz 11
如果要读取单个整数,请执行以下操作:
int x;
fscanf(file, "%d", &x );
Run Code Online (Sandbox Code Playgroud)
如果需要,可以这样做来读取动态分配变量中的单个整数:
int *x = malloc(sizeof(int));
fscanf(file, "%d", x );
Run Code Online (Sandbox Code Playgroud)
如果需要整数数组,请执行以下操作:
int *x = malloc(sizeof(int) * DESIRED_ARRAY_SIZE);
fscanf(file, "%d", &x[i] );
Run Code Online (Sandbox Code Playgroud)
%d期望指向a的指针int,但是x[i]是int,所以你需要使用address-of运算符(一元&)来获取list元素的地址.
您需要为结果分配一些空间.
int *x; // declares x
x = malloc( 600000 * sizeof(int) ) // and allocates space for it
for (int i = 0; i < 600000; ++i ) {
fscanf(file, "%d", &x[i] ); // read into ith element of x
}
Run Code Online (Sandbox Code Playgroud)