June 20th, 2003, 02:52 PM
C - Programming. Assigning an integer to a character array
root@galaxian:~# gcc -o from_octal_to_string from_octal_to_string.c
from_octal_to_string.c: In function `convert_from_octal_to_string':
from_octal_to_string.c:17: incompatible types in assignment
Line 17 is a problem
How do I assign a number 144 to a character array ?
1 #include <stdio.h>
5 unsigned long octal_long;
6 int var_oct = 1015;
7 int var1 = 0;
8 char array_char;
10 var1 = (var_oct - 7) / 7; /* equal 144 */
11 printf ("var1 = %d\n", var1);
13 array_char = var1; --> THE PROBLEM IS HERE
15 /*convert from octal value to string. 144 is a d */
16 octal_long = strtoul (var1, NULL, 8);
17 printf ("octal_long = %c\n", octal_long);
June 20th, 2003, 03:22 PM
You're trying to assign an integer to character array on Line 13.
Can't you just use sprintf()?
Here is a little test I ran:
That's if you actually need to save the data from val1 into array_char. If you just needed to print it out once or so, just use printf():
int val1 = 144;
printf("array_char is %s",array_char);
// array_char is 144
printf("val1 is %d",val1);
June 20th, 2003, 03:23 PM
I'm not sure what you're trying to do with the rest of your code. Remember, every single number stored in a computer is in binary (even BCD and packed decimal, though those are specially-formatted binary numbers). It's only the human-readable representations of those binary numbers that end up being octal or hexadecimal or decimal or sexagesimal (base-60, which we use all the time). So the very basis of what you are doing in that program seems very suspect to me.
However, if you want to convert a binary number to its octal representation, then that would be with the %o family of format specifiers (%o for unsigned int, %ho for unsigned short, %lo for unsigned long):
BTW, I hadn't used the strto** family of functions before, so I didn't know before that strtoul enables you to convert a string representing a number of any base. Cool.
/*17 */ printf ("octal_long = %lo\n", octal_long);
June 20th, 2003, 05:41 PM
Re: C - Programming. Assigning an integer to a character array
I think you are assigning an int to a constant pointer since the name of an array is a constant pointer...