如何在C中转换u_char*到char[] ?

[英]How to convert u_char* to char[] in C


I am working with snmp and the requests->requestvb->val.string function returns me a u_char* and I am trying to store that into a char[255].

我正在处理snmp和请求->requestvb->val。string函数返回一个u_char*,我试图将其存储到char[255]中。

u_char newValue = *(requests->requestvb->val.string)
char myArray[255];

I have tried a few approaches to copy the contents of newValue into myArray but everything seems to segfault. What am I doing wrong?

我已经尝试了一些方法来将newValue的内容复制到myArray中,但是一切似乎都是分段的。我做错了什么?

I have tried memcpy(myArray, newValue);

我尝试过memcpy(myArray, newValue);

Another attempt strncopy(myArray, newValue, sizeof(myArray));

另一个尝试strncopy(myArray, newValue, sizeof(myArray));

What am I doing wrong?

我做错了什么?

1 个解决方案

#1


3  

Your newValue is of type char, and for all intents and purposes, your myArray is of type char*.

您的newValue是char类型,对于所有意图和目的,您的myArray是char*类型。

First off, I'm going to assume that you're using memcpy correctly, and that you're passing in 3 parameters instead of 2, where the 3rd parameter is the same as the one you use in strncpy.

首先,我假设你正确地使用了memcpy,并且你正在传递3个参数而不是2,其中第三个参数与你在strncpy中使用的参数相同。

When you try using strncpy or memcpy, you're going beyond the one character "limit" in newValue when attempting to copy everything to myArray.

当您尝试使用strncpy或memcpy时,在尝试将所有内容复制到myArray时,您将超越newValue中的一个字符“limit”。

The fix should be quite simple:

解决方法应该很简单:

u_char* newValue = requests->requestvb->val.string;

Once you've done that, this should work. Of course, that's assuming that the size of myArray is in fact greater than or equal to 255 :)

一旦你这样做了,这就应该奏效了。当然,这假设myArray的大小实际上大于或等于255:)

As a side note (and this should go without saying), please make sure that your myArray has a null terminating character at the end if you ever plan on printing it. Not having one after performing copy operations, and then trying to print is a very common mistake and can also lead to seg faults.

作为附注(这应该不用说),请确保您的myArray在结束时有一个空终端字符,如果您打算打印它的话。在执行复制操作之后没有一个,然后尝试打印是一个非常常见的错误,也会导致seg错误。

关注微信公众号

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/04/05/27c227123a8af851792c327cc52c2a40.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com