访问结构成员时返回了字节,并且在打印结构变量地址时发生了分段错误 [英] bytes were returned when we access the structure member and Segmentation fault occurs when printing structure variable address
问题描述
我创建了一个struct
,并为该结构分配了一个指针变量.当我尝试打印该变量的地址时,它可以正确打印.在使用此pointer
结构变量将值分配给该结构的成员之一后,当我尝试打印pointer
变量的地址时,我得到了 segmentation fault
.
I created one struct
and assigned one pointer variable to that structure. When I tried to print the address of that variable it prints correctly. After assign value to one of the member of the structure using this pointer
structure variable, when i tried to print the address of the pointer
variable I got segmentation fault
.
#include <stdio.h>
typedef struct node {
char mem;
double mem2;
char mem3;
int mem4;
char mem5;
char mem6;
}NODE;
int main()
{
NODE * m;
printf("%u",&m);
return 0;
}
我得到的输出为3014616488.当我将变量分配给结构成员之一时,
I got output as 3014616488. When I assigned variable to one of the structure member,
#include <stdio.h>
typedef struct node {
char mem;
double mem2;
char mem3;
int mem4;
char mem5;
char mem6;
}NODE;
int main()
{
NODE * m;
m->mem3 = 'A';
printf("%u",&m);
return 0;
}
我遇到了细分错误.当我这样做的时候
I got segmentation fault. When I did like this
#include <stdio.h>
typedef struct node {
char mem;
double mem2;
char mem3;
int mem4;
char mem5;
char mem6;
}NODE;
int main()
{
NODE * m;
printf("%u",&m->mem3);
return 0;
}
我得到16作为输出.我不知道16是怎么来的.这真的让我很挣扎.请任何人帮助我了解到底发生了什么.预先感谢
I got 16 as output . I don't know how 16 came. It really struggling my mind. Please any one help me to get know what exactly happening. Thanks in advance
推荐答案
因为它没有分配任何内存
Because its not allocated any memory
NODE * m = malloc(sizeof(NODE));
// Do stuffs
free(m);
所以尝试一下:
int main()
{
NODE * m = malloc(sizeof(NODE));
m->mem3 = 'A';
printf("%u",&m->mem3);
free(m);
return 0;
}
通知:
Notice :
Int c
或c++
(如果您声明了pointer
),则为pointer
保留了一些内存(通常在 stack
上).指针未初始化的方式,这意味着它指向的地址与最后一个相应存储位置中的地址相对应. (这是code
的第一部分起作用的原因.)
Int c
or c++
if you declare a pointer
, some memory is reserved for the pointer
(usually on the stack
). How ever the pointer is not initialized, meaning that it points to the address corresponding to what was in the respective memory location last. (This is the reason that first section of code
is worked).
这篇关于访问结构成员时返回了字节,并且在打印结构变量地址时发生了分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!