gpt4 book ai didi

核心转储试图在结构中创建 newVector(array 2D)

转载 作者:太空宇宙 更新时间:2023-11-04 06:49:15 25 4
gpt4 key购买 nike

所以我尝试在结构中创建一个简单的二维数组,并读取文件中某些坐标的值。

此时我已经有了所有的内部函数,当我试图在“get_coords”函数上获取坐标时,我遇到了一个段错误。如果我在“int main”上编写所有完全相同的代码而不是使用函数,它就可以工作。

代码:

            #include <stdio.h>
#include <stdlib.h>

// structure
typedef struct coordinates{
double **a;
} coord;

// counts the nmbr of points
int count(){
int i;
int a1, a2, a3;
FILE *fp;
fp = fopen("abc.txt", "r+");
while (fscanf(fp, "%d %d %d", &a1, &a2, &a3) != EOF){
i++;
if (feof(fp)){
break;
}
}
fclose(fp);
return(i);
}

// creates new structure with the right size of memory allocated
coord *newVector(size_t s){
coord *v;
int j;
v = malloc(sizeof(coord));

v->a = malloc(sizeof(double*)*3);

for (j=0; j<3; j++){
v->a[j] = malloc(sizeof(double)*s);
}

}

void get_coords(coord *points){
int i=0;
FILE *fp;
fp = fopen("abc.txt", "r+");
while (fscanf(fp, "%le %le %le", &points->a[i][0], &points->a[i][1], &points->a[i][2]) != EOF){
i++;
}
fclose(fp);
}


int main(){
int i = 0, j=0;

coord *points;

i = count();

points = newVector(i);

get_coords(points);

for (i=0; i<3; i++){
printf("%lf %lf %lf\n", points->a[i][0], points->a[i][1], points->a[i][2]);
}
}

abc.txt:

1 2 3
4 5 6
7 8 9

感谢大家的帮助。

杯子,迪伦。

PS:这只是我想要的原型(prototype)。

最佳答案

count() 中,您正在递增一个未初始化 变量,调用未定义行为 (UB)。

改变这个:

int count() {
int i;

为此:

int count() {
int i = 0;

newVector() 返回动态分配的内存。

改变这个:

coord *newVector(size_t s) {
...
}

为此:

coord *newVector(size_t s) {
...
return v;
}

解决这些问题后,您应该会看到以下输出:

1.000000 2.000000 3.000000
4.000000 5.000000 6.000000
7.000000 8.000000 9.000000

不是问题,但我会使用 %lf 作为 fscanf() 中的格式说明符,而不是 %le

而且,在count()中,这个return(i);和这个return i;是一样的。括号是多余的。

TODO:释放动态分配的内存(我假设您跳过了提供 MCVE 的那部分)。


专业提示:下次编译时启用警告标志。在这种情况下,他们已经为您找到了问题所在。例如,在 GCC 中,我会得到这个:

gsamaras@myPc:~$ gcc -Wall  main.c
main.c: In function ‘main’:
main.c:51:28: warning: unused variable ‘j’ [-Wunused-variable]
int i = 0, j=0;
^
main.c: In function ‘newVector’:
main.c:37:13: warning: control reaches end of non-void function [-Wreturn-type]
}
^

最后一个警告是我回答中的第二点。

关于核心转储试图在结构中创建 newVector(array 2D),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53851445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com