C中通过引用传递2D动态分配的双精度数组
我正在尝试将字符串转换为动态双精度数组。我的字符串的每个空格代表一列,每个“;”代表一个新行。当此代码运行时,它仅适用于 *F[0][col] 时。当它到达 *F[1][col] 时,它给我错误“CCode.exe 中 0x00e4483c 处未处理的异常:0xC0000005:访问冲突读取位置 0xcccccccc。”有人知道为什么吗?
void main(void) {
double **F = NULL;
F = malloc(row * sizeof (double *));
for (m=0; m < row;m++) {
F[m] = malloc(col * sizeof(double ));
}
FParser(string, &F);
for (m=0;m<rowF;m++)
free(F[m]);
free(F);
}
void FParser(char string[256], double ***F) {
while (dummyChar_ptr != NULL) {
dummyChar_ptr = strtok(dummyChar_ptr," ");
while ((dummyChar_ptr) != NULL) {
*F[row][col] = atof(dummyChar_ptr);
dummyChar_ptr = strtok(NULL," ");
col++;
}
col=0;
row++;
strcpy(dummyChar,string);
dummyChar_ptr = strtok(dummyChar,";");
for (x=0;x<row;x++)
dummyChar_ptr = strtok(NULL,";");
}
//example String: 1 0.1 0 0; 0 1 0 0; 0 0 1 0.1; 0 0 0 0.1
I'm trying to convert my string into a dynamic array of doubles. Each space of my string represents a column, each ";" represents a new row. When this code runs, it only works for when *F[0][col]. When it gets to *F[1][col] it gives me the error "Unhandled exception at 0x00e4483c in CCode.exe: 0xC0000005: Access violation reading location 0xcccccccc." Anyone know why?
void main(void) {
double **F = NULL;
F = malloc(row * sizeof (double *));
for (m=0; m < row;m++) {
F[m] = malloc(col * sizeof(double ));
}
FParser(string, &F);
for (m=0;m<rowF;m++)
free(F[m]);
free(F);
}
void FParser(char string[256], double ***F) {
while (dummyChar_ptr != NULL) {
dummyChar_ptr = strtok(dummyChar_ptr," ");
while ((dummyChar_ptr) != NULL) {
*F[row][col] = atof(dummyChar_ptr);
dummyChar_ptr = strtok(NULL," ");
col++;
}
col=0;
row++;
strcpy(dummyChar,string);
dummyChar_ptr = strtok(dummyChar,";");
for (x=0;x<row;x++)
dummyChar_ptr = strtok(NULL,";");
}
//example String: 1 0.1 0 0; 0 1 0 0; 0 0 1 0.1; 0 0 0 0.1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
[]
的优先级高于 C 中的一元*
,因此*F[row][col]
实际上是*(F [row][col])
,并且您正在索引到错误的内存位置。尝试
(*F)[行][列])
。顺便说一句,
FParser
没有理由采用double***
。F
已经是一个指针;就这样通过吧。您需要使用额外间接级别的唯一原因是FParser
需要修改main()
的F
指向的内容。其他杂项建议:
malloc
是否成功。strcpy
。char string[256]
实际上并不能保证输入参数是一个包含 256 个(或更多)元素的数组,因此在我看来,这是毫无意义的,也可能是char * 字符串
。[]
has a higher precedence than unary*
in C, so*F[row][col]
is actually*(F[row][col])
, and you're indexing into the wrong memory location.Try
(*F)[row][col])
.Incidentally, there's no reason for
FParser
to take adouble***
anyway.F
is already a pointer; just pass that. The only reason you'd need to use an extra level of indirection is ifFParser
needed to modify whatmain()
'sF
points to.Other miscellaneous bits of advice:
malloc
succeeded.strcpy
unless you've checked that the source string won't overflow the destination buffer.char string[256]
doesn't actually guarantee that the input argument is an array of 256 (or more) elements, so IMO it's kind of pointless and might as well bechar* string
.