通过指针为struct的成员赋值

时间:2012-09-20 17:29:20

标签: c pointers structure

我可能会做一些令人难以置信的愚蠢错误,但我找不到它,很简单:

int main()
{

typedef struct drzemka typ;
struct drzemka {     
int strukcje;
};
typ *d;
d->strukcje = 1;
}

并且无效

4 个答案:

答案 0 :(得分:4)

现在你的指针没有设置为有效的内存。您需要为struct

分配此内存
#include <stdlib.h>
/* ... */
typ *d = malloc(sizeof(typ));

与您分配的任何记忆一样,请记得在完成后将其释放:

free(d);

答案 1 :(得分:3)

您需要将d分配给有效的内容。你必须给它一些记忆。现在它是一个类型typ的指针,它指向什么都没有。然后你试图不顾一切。

将堆中的一些内存分配给指针并按原样使用它:

typ *d = malloc(sizeof(typ)); 
d->strukcje = 1;
free(d);

或者将静态副本放在堆栈上:

typ d;
d.strukcje = 1; 

答案 2 :(得分:0)

正确的代码是:

struct drzemka {     
int strukcje;
};
typedef struct drzemka typ;


int main()
{
   typ d;
   d.strukcje = 1;
}

int main()
{
 typ* d = (typ *) malloc(sizeof(typ));
 d->strukcje = 1;

}

答案 3 :(得分:0)

试试这个:

typedef struct drzemka {     
    int strukcje;
}typ;

int main() {
    typ d;
    typ * p = &d;
    p->strukcje = 1;
    printf("The value of strukcje is %d",p->strukcje);
}
相关问题