简体   繁体   English

在函数中初始化的结构异常

[英]Struct initialized in function behaving weirdly

In my project, i have created 3 different typedef struct types: 在我的项目中,我创建了3种不同的typedef struct类型:

typedef struct Point 
{ 
    float x; 
    float y;
    float z;
} Point;

typedef struct Triangle 
{ 
    Point A; 
    Point B;
    Point C;
    unsigned char color[3];//RGB
} Triangle;

typedef struct Structure 
{ 
    Triangle* triangles; 
    unsigned int nt; //number of triangles in array
} Structure;

As you might have noticed, the type Structure has a dynamic sized array of Triangle s, so i'll also post here the memory allocation and freeing functions: 您可能已经注意到, Structure类型具有一个动态大小的Triangle数组,因此我还将在此处发布内存分配和释放函数:

Structure newStructure(unsigned int nt)
{
    Structure S;
    Triangle* tri = malloc ((nt) * sizeof(Triangle));
    if (tri!=NULL) 
    {
        S.triangles = tri;
        S.nt = nt;
    }
    else S.nt = 0;
    return S;
}

void delStructure (Structure S) 
{
    if (S.triangles != NULL) free (S.triangles);
}

Then i wanted to make a function to add a Triangle to a current Structure using the following syntax: S = addTriangle(T,S) . 然后,我想制作一个函数,使用以下语法将Triangle添加到当前StructureS = addTriangle(T,S) This is what i have: 这就是我所拥有的:

Structure addTriangle(Triangle T, Structure S)
{

    Structure R = newStructure(S.nt+1);
    int i=0;

    while(i++<S.nt) R[0].triangles[i] = S.triangles[i];
    R[0].triangles[S.nt] = T;

    delStructure(S); //Is this necessary?

    return R[0];
}

It shows no error messages when compiling, however when i use the function, the first Triangle on the array gets random values. 编译时没有显示错误消息,但是当我使用该函数时,数组上的第一个Triangle获取随机值。 To be more clear, if I have a Structure S with Triangles T1 and T2 in the array, and then i use S = addTriangle(T3,S) the result will be a Structure with the following array of Triangle s: {T?,T2,T3} , where T? 更明确地说,如果我在数组中具有三角形T1T2Structure S ,然后使用S = addTriangle(T3,S)则结果将是具有以下Triangle s数组的Structure{T?,T2,T3} ,其中T? has apparently random values. 具有明显的随机值。

Why is this happening? 为什么会这样呢?

while(i++<S.nt) R[0].triangles[i] = S.triangles[i];

should be something like 应该是这样的

for (i=0; i<S.nt; i++) {
    R.triangles[i] = S.triangles[i];
}

Currently, you skip assigning the first element of R.triangles and assign its second last element by reading beyond the end of S.triangles . 目前,您跳过分配的第一要素R.triangles并通过读取超出年底分配倒数第二个元素S.triangles You can fix this by deferring incrementing i until the end of each loop. 您可以通过将递增i推迟到每个循环结束来解决此问题。 (You could continue to do this using a while loop; I found a for loop clearer.) (您可以使用while循环继续执行此操作;我发现了for循环清除器。)

Also, all use of R[0] can (should) be replaced by R . 同样, R[0]所有使用都可以(应)由R代替。 R is a single structure, not an array. R是单个结构,而不是数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM