【问题标题】:Structure..can anyone figure this out?结构..任何人都可以解决这个问题吗?
【发布时间】:2018-05-30 19:11:17
【问题描述】:

为什么 p->p1 产生 1,而 s2.p1 产生 0?它们都指向完全相同的东西,而 p->p2 和 s2.p2 不会发生这种情况。

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

struct S1{
    int p1, p2;
};
struct S2{
    int p1;
    struct S1 s1;
    int p2;
};

int main (void){
    int s = 0;
    struct S2 s2 = {1,2,3,0};
    struct S2 *p;
    p = (struct s2 *)malloc(sizeof(struct S2));

    *p = s2;


    s2.p1 = 0;
    printf("p->p1 %d,s2.p1 %d   \n\n",p->p1, s2.p1 );
    printf("%d\t %d\t %d\t %d\t %d\n",p->p1 , s2.p1 , p->p2 , p->s1.p2 );
    s = p->p1 + s2.p1 + p->p2 + p->s1.p2;

    free(p);
    printf("%d", s);
    return 0;
    }

【问题讨论】:

  • @WeatherVane 这是错误的。看到问题了吗? p = (struct s2 *)malloc(sizeof(struct S2));
  • 无论如何,p-&gt;p1 与s2.p1 不同。 p 获取s2 内容的副本,但不指向s2。
  • test.c(17):警告 C4133:'=':不兼容的类型 - 从 's2 *' 到 'S2 *'。 test.c(24): 警告 C4473: 'printf' : 没有为格式字符串传递足够的参数。 test.c(24):注意:占位符及其参数需要 5 个可变参数,但提供了 4 个。 test.c(24):注意:格式字符串 '%d' 需要缺少的可变参数 5。
  • .code.tio.c:17:7: warning: assignment to ‘struct S2 *’ from incompatible pointer type ‘struct s2 *’ .code.tio.c:24:34: warning: format ‘%d’ expects a matching ‘int’ argument
  • 旁白:谁或什么文字建议(struct s2 *)p = (struct s2 *)malloc(sizeof(struct S2));中的演员?

标签: c pointers structure


【解决方案1】:

因为您将 s2 的内容复制到 p 指向的结构中,然后您更新了 s2 的内容。

【讨论】:

    【解决方案2】:

    为什么 p->p1 产生 1, ....?

    因为代码最后分配了 p-&gt;p1 的值为 1 和 ****

    //              v--- p1 member
    struct S2 s2 = {1,2,3,0};
    struct S2 *p;
    p = (struct s2 *)malloc(sizeof(struct S2));
    *p = s2;  // ****  This copies the contents of `s2` to `*p`.
    

    为什么 ... s2.p1 产生 0?

    因为代码稍后将0分配给s2.p1

    //              v--- p1 member
    struct S2 s2 = {1,2,3,0};
    ...
    s2.p1 = 0;
    

    它们(p-&gt;p1、s2.p1)都指向完全相同的东西

    不,他们没有。 p 是从分配的内存中分配了一个值的指针,s2 是用struct S2 s2 定义的对象。分配的内存和对象s2 不在同一个位置。 s2 作为一个结构,从不指向任何东西。 @melpomene

    【讨论】:

      猜你喜欢
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2023-04-01
      • 2013-06-03
      相关资源
      最近更新 更多