[英]How to copy integer array contents to a character pointer?
I have a character pointer , char *buf;
我有一个字符指针
char *buf;
I have a array of integers , int console_buffer[256];
我有一个整数数组,
int console_buffer[256];
I need to copy the console_buffer
contents to character buf. 我需要将
console_buffer
内容复制到字符buf。 How do I do this? 我该怎么做呢? The
buf
and console_buffer
are part of different structures. buf
和console_buffer
是不同结构的一部分。
Going by your comment, 根据您的评论,
buf = malloc(256); // 257 if console_buffer may be full without EOF
/* if you want to allocate just as much space as needed, locate the EOF in console_buffer first */
for(int i = 0; i < 256 && console_buffer[i] != -1; ++i){
buf[i] = (char)console_buffer[i];
}
If you already allocated the memory for buf
, and if each integer is between 0 and 9, you can do: 如果您已经为
buf
分配了内存,并且每个整数都在0到9之间,则可以执行以下操作:
for(int i = 0; i < 256; i++)
{
buf[i] = '0' + console_buffer[i]; /* convert 1 to '1', etc. */
}
If the integers are larger than 9, you can use the sprintf
function. 如果整数大于9,则可以使用
sprintf
函数。
Reading your new comment, perhaps you can also achieve your goal by reading from console buffer directly to an array of chars until you have -1
(check by integers comparison, or by strcmp
, or by comparing the 2 last characters to 0
and to 1
). 阅读您的新注释,也许您还可以通过从控制台缓冲区直接读取一个char数组直到达到
-1
(通过整数比较或strcmp
进行检查,或者通过将最后2个字符与0
和1
进行比较来实现目标。 )。
I think this is a better way to convert values to char
s 我认为这是将值转换为
char
的更好方法
int i = 0;
while (i <= 256) {
buf[i] = (char) console_buffer[i];
i++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.