|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
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> 2 3 convert_from_octal_to_string() 4 { 5 unsigned long octal_long; 6 int var_oct = 1015; 7 int var1 = 0; 8 char array_char[4]; 9 10 var1 = (var_oct - 7) / 7; /* equal 144 */ 11 printf ("var1 = %d\n", var1); 12 13 array_char = var1; --> THE PROBLEM IS HERE 14 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); 18 } 19 20/********************************************/ 21 22 main() 23 { 24 convert_from_octal_to_string(); 25 } |
|
#2
|
|||
|
|||
|
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: Code:
int val1 = 144;
char array_char[4];
sprintf(array_char,"%d",val1);
printf("array_char is %s",array_char);
// array_char is 144
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(): Code:
printf("val1 is %d",val1);
|
|
#3
|
||||
|
||||
|
Quote:
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): Code:
/*17 */ printf ("octal_long = %lo\n", octal_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. |
|
#4
|
|||
|
|||
|
Re: C - Programming. Assigning an integer to a character array
Quote:
I think you are assigning an int to a constant pointer since the name of an array is a constant pointer... |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > C - Programming. Assigning an integer to a character array |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|