【发布时间】:2011-07-18 16:36:52
【问题描述】:
对于学校的作业,我们必须使用结构体来制作矩阵,该矩阵可以为无限量的矩阵存储无限量的点。 (理论上无限)
对于作业,我决定使用 calloc 和 realloc。矩阵的大小如何:每次达到其点的限制时,它的大小都会翻倍(因此它从 1 开始,然后到 2,然后是 4,依此类推)。每次添加矩阵时,它的大小也会翻倍。
这就是我的问题所在。添加初始矩阵后,它会添加第二个矩阵名称和点,它给了我以下内容:
B???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
B 是我想要的部分(因为我稍后会使用 strcmp),但是 ?标记不应该在那里。 (显然)
我不确定它为什么会这样做。由于代码是模块化的,因此要获取其中的一部分来准确显示它是如何进行的并不是很容易。
注意:我可以通过它的方法访问矩阵的点:MyMatrix[1].points[0].x_cord;(这只是一个例子)
产生问题的示例代码:
结构:
struct matrice {
char M_name[256];
int num_points[128];
int set_points[128];
int hasValues[1];
struct matrice_points * points;
} * MyMatrix;
struct matrice_points {
int set[1];
double cord_x;
double cord_y;
};
设置矩阵函数:
void setupMatrix(){
MyMatrix = calloc(1, sizeof(*MyMatrix));
numMatrix = 1;
}
增长矩阵函数:
void growMatrix(){
MyMatrix = realloc(MyMatrix, numMatrix * 2 * sizeof(*MyMatrix));
numMatrix = numMatrix * 2;
}
添加矩阵函数,在矩阵增长一次后输出此问题。
void addMatrix(char Name, int Location){
int exists = 0;
int existsLocation = 0;
for (int i = 0; i < numMatrix; i++){
if (strcmp(MyMatrix[i].M_name, &Name) == 0){
exists = 1;
existsLocation = i;
}
}
*MyMatrix[Location].M_name = Name;
printf("Stored Name: %s\n", MyMatrix[Location].M_name);
*MyMatrix[Location].num_points = 1;
*MyMatrix[Location].set_points = 0;
*MyMatrix[Location].hasValues = 1;
MyMatrix[Location].points = calloc(1, sizeof(*MyMatrix[Location].points));
}
【问题讨论】:
-
@user667163:你能准备一个单文件的最小代码示例来重现问题吗?不看一些代码很难提供帮助。
-
至少发布 sn-ps 显示 1. 你的矩阵结构是如何定义的,2. 你最初是如何分配它的,3. realloc 调用,最后你是如何得到这个输出的(你是如何打印的矩阵)
-
@Mat, @Marcelo Cantos - 添加了代码片段