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.
-
5This question is ill-posed. How do you want to convert between int and char?David Heffernan– David Heffernan2011-11-19 16:20:44 +00:00Commented Nov 19, 2011 at 16:20
-
I will tell you why I need this. I am trying to implement read system call. The console_buffer is declared as integer array since when EOF is encountered it returns -1, so I know I have to stop here. Actually console_buffer will contain characters. Finally after console_biffer is read, I need to copy it to my Process control block structure which has a char * buf member.Maxwell– Maxwell2011-11-19 16:29:07 +00:00Commented Nov 19, 2011 at 16:29
-
You can do this with a simple loop. What have you tried so far?David Heffernan– David Heffernan2011-11-19 16:33:35 +00:00Commented Nov 19, 2011 at 16:33
Add a comment
|
3 Answers
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];
}
2 Comments
Maxwell
Thanks. My question is since I am storing characters in console_buffer which would be stored as ascii values, will (char)console_buffer[i] convert them back to characters? or do I need to handle this in different way?
Daniel Fischer
Yes, casting to
char does exactly what you want, since what you stored in console_buffer is in the range of char. There's a possible problem if char is signed, though. The getc family returns unsigned chars cast to int, these may be out of range for signed char, then the conversion is not guaranteed (but it almost certainly does the right thing).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).
2 Comments
Maxwell
Will the following code work? for(i=0; i< 256; i++){ pcb -> buf = (char*) console_buffer(i); } Pardon me if I sound silly , I have just started using pointers, so not yet comfortable with it.
Maxwell
@Igor Oks: I dont understand. In my console_buffer integer array characters are going to be stored like 'C','I' ... ( I guess the ascii values will be stored am I right? ) and once all is read, -1 integer will be stored at the end.