简体   繁体   English

将结构体类型转换为int

[英]Type casting a struct into int

Hello every one I want to ask a question about type casting.It confuses me two much. 大家好,我想问一个关于类型转换的问题。这让我很困惑。 I am writing a code in which I am using an already created function having prototype like this. 我正在编写一个代码,其中使用的是具有这样的原型的已创建函数。

void function (uint8_t * output , const uint_8 * buffer , int bufferlen);

it is called like this 像这样

const char * text = "some text";
uint8_t result[16];
function (result, (uint8_t *)text , strlen(text)); 

But my problem is that I have to call the same and pass it a struct so I call the function like this 但是我的问题是我必须调用相同的函数并将其传递给结构,所以我这样调用函数

const struct mystruct * ms;

function (result, (uint8_t *)ms , sizeof(*ms)); 

But it giving me segmentation fault. 但这给了我分割错误。 can any one guide me what should I pass in place of third argument. 任何人都可以指导我代替第三个论点我该怎么做。

Thanks 谢谢

I ma using C programming linux 我正在使用C编程Linux

How big is the Struct? 结构有多大? Your result has a particular length, 16, I'm guessing that the function your are calling is copying into result. 您的结果有一个特定的长度16,我猜您正在调用的函数正在复制到结果中。 If it's too small you have a problem. 如果太小,您会遇到问题。

You declared an uninitialized pointer that does not point at valid memory. 您声明了未指向有效内存的未初始化指针。 That is why the function crashes when it tries to use that pointer. 这就是为什么函数在尝试使用该指针时崩溃的原因。 Use this instead: 使用此代替:

struct mystruct *ms = (struct mystruct *) malloc(sizeof(struct mystruct)); 
function (result, (uint8_t *)ms, sizeof(struct mystruct));  
free(ms);

Or: 要么:

struct mystruct ms; 
function (result, (uint8_t *)&ms, sizeof(ms));  

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

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