C、赋值结构指针改变赋值右侧内容

C, assignment of struct pointers changes the content of the right side of assignment

提问人:S. Bing 提问时间:6/26/2018 最后编辑:S. Bing 更新时间:6/26/2018 访问量:682

问:

我有以下结构:

typedef struct{
    char *name;
    int size;
    void *data;
} Struct1;
typedef struct st2{
    char *name;
    struct st2 **Struct2array;
    Struct1 **Struct1array;
    int Struct1_n;
    int Struct2_n;
} Struct2;

其中 Struct2 中的双精度指针用作指向其他 Struct2 或 Struct1 的指针的动态数组。Struct1 中的数据用作动态数组来存储一些数据。Struct1_n 和 Struct2_n 表示其各自动态数组内的元素数。

当我创建一个 Struct1 类型的变量时,我通过将 char * 转换为空 * 并使用 memcpy 将其复制到数据中来填充数据。如果我然后将数据转换回 char 指针,我可以取回内容,它们通常是相同的。但是,由于某种原因,Struct1 中的数据指向的值在以下行之后发生变化:

struct2pointer->Struct1array[struct2pointer->Struct1_n - 1] = struct1pointer;

例子:

printf("%d\n", *(char *)(struct1pointer->data));

在有问题的行之后立即将 struct1Pointer->data 的 1stbyte 的值给出为 -96,而不管它之前立即打印的值(与 memcpy-d 到 data 中的值相同)。如果我在将指针转换为字符指针(第 2 个字节)之前将 1 添加到指针,它总是给出 32,如果我添加 2(第 3 个字节),它总是给出 96,依此类推。

当 struct1pointer 位于赋值运算符的右侧时,为什么会发生这种情况,可以做些什么来解决这个问题?

编辑:

内容更改的功能:

void struct2_addstruct1(Struct2 struct2pointer, Struct1 *struct1pointer){
    struct2->Struct1_n++;
    struct2pointer->Struct1array = realloc(struct2pointer->Struct1array, struct2->Struct1_n * sizeof(Struct1 *)); //edited to remove increment that was added on accident, isn't in the original code
    struct2pointer->Struct1array[struct2pointer->Struct1_n - 1] = struct1pointer;
}

创建 Struct1 的函数:

void struct1_init(Struct1 *s, char *name, void *data, int size){
  s->name = malloc(strlen(name) + 1);
  strcpy(s->name, name);

  s->size = size;

  s->data = malloc(size);
  memcpy(s->data, data, size);
}

这是在创建 struct1 时调用该函数的方式:

Struct1 *s;
struct1_init(s, name, data, size);

名称、数据和大小是从外部提供的,但应该与问题无关。

c 指针 struct void-pointers 赋值运算符

评论

2赞 Paul Ogilvie 6/26/2018
这些指针是如何分配的?请向我们展示更多相关代码。问题可能不在于作业本身。
3赞 Jabberwocky 6/26/2018
PLease 显示一个最小的可重现示例
0赞 Bathsheba 6/26/2018
我的钱用于越界元素访问尝试。
0赞 S. Bing 6/26/2018
void Struct1_init(Struct1 *s, char *name, void *data, int size){ s->name = malloc(strlen(name) + 1); strcpy(s->name, name); s->size = size; s->data = malloc(size); memcpy(s->data, data, size); }
0赞 Paul Ogilvie 6/26/2018
它本身是如何分配的?请编辑您的答案以提供信息;不要将其放在未格式化的注释中。s

答:

1赞 Support Ukraine 6/26/2018 #1

请看这段代码:

Struct1 *s;
struct1_init(s, name, data, size);

这里是未初始化的。s

但是,在函数中,您确实假设指针已经指向 .struct1_initsStruct1

也许你忘记了一个 - 比如:malloc

Struct1 *s = malloc(sizeof *s);
struct1_init(s, name, data, size);