Maxwell
Maxwell

Reputation: 429

How to copy integer array contents to a character pointer?

I have a character pointer , char *buf; I have a array of integers , int console_buffer[256]; I need to copy the console_buffer contents to character buf. How do I do this? The buf and console_buffer are part of different structures.

Upvotes: 0

Views: 1127

Answers (3)

manikandan
manikandan

Reputation: 11

I think this is a better way to convert values to chars

int i = 0;
while (i <= 256) {
    buf[i] = (char) console_buffer[i];
    i++;
}

Upvotes: 0

Daniel Fischer
Daniel Fischer

Reputation: 183908

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];
}

Upvotes: 1

Igor
Igor

Reputation: 27248

If you already allocated the memory for buf, and if each integer is between 0 and 9, you can do:

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.


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).

Upvotes: 0

Related Questions