对于 C 初学者来说,我在理解数组、指针和数组指针时遇到了一些问题。不幸的是,这里提供的信息对我没有多大帮助,因为它们都处理“更简单”的问题。这是我的代码:
/* random.c */
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(){
double particles[4][22];
int seed,i,x,y;
double px_buf, py_buf, pz_buf;
seed=time(NULL);
srand(seed);
/* The random numbers are generated between 1E-12 and 10E-12 */
/*Double precision floats support up to 15 decimal places*/
for(i=0;i<20;i++){
px_buf=((double)rand()/RAND_MAX)*9001E-15;
py_buf=((double)rand()/RAND_MAX)*9001E-15;
pz_buf=((double)rand()/RAND_MAX)*9001E-15;
particles[0][i]=px_buf;
particles[1][i]=py_buf;
particles[2][i]=pz_buf;
printf("(step: %i) The following noise momentum was generated: (%.15E,%.15E,%.15E)\n",i,px_buf,py_buf,pz_buf);
}
sscanf("p[20] = nullvector(45.0000000000106,33.03951484238976,14.97124733712793,26.6317895033428)", \
"p[20] = nullvector(%lf,%lf,%lf,%lf)",&particles[3][20],&particles[0][20],&particles[1][20],&particles[2][20]);
for(y=0;y<22;y++){
for(x=0;x<3;x++){
printf("%.15E \t", particles[x][y]);
}
printf("\n");
}
return 0;
}
这段代码运行良好,但如您所见,最后四个 (y=21) 数组条目是“空的”,我想以与现在使用 sscanf 行相同的方式填充它。
我想用合适的解析器函数替换 sscanf 部分,但我完全不知道如何正确传递指针,尤其是如何为 sscanf 使用地址 (&) 一元运算符。这是我的初步解析器功能:
/* parse.c */
void parser(char *input, double **particles){
sscanf(input, "p[20] = nullvector(%lf,%lf,%lf,%lf)", \
&particles[3][20],&particles[0][20],&particles[1][20],&particles[2][20]);
printf("energy: %E, p: (%E, %E, %E)\n",particles[3][20], \
particles[0][20],particles[1][20],particles[2][20]);
}
正如你所看到的,我主要对前面有“nullvector(”的四个双精度值感兴趣,我想从字符串中取出这些值并将它们写入多数组“粒子”的第 21“行”。
但是当我添加一个
#include "parse.c"
(...)
parse("p[20] = nullvector(45.0000000000106,33.03951484238976, \
14.97124733712793,26.6317895033428)",particles);
到主要功能,它给了我以下错误:
[darillian@quantumbox rng]$ gcc random.c -Wall -pedantic -o ../../bin/random
random.c: In function ‘main’:
random.c:29:2: warning: passing argument 2 of ‘parse’ from incompatible pointer type [enabled by default]
In file included from random.c:4:0:
parse.c:1:6: note: expected ‘double **’ but argument is of type ‘double (*)[22]’
我究竟做错了什么?;D