int k=5;
char* result = (char *)malloc(100 * sizeof(char));
result[count] = k;
Considering the above code, if I print the contents of result[count] it prints smiley symbols. I tried like below,but of no use.
result[count]=(char)k;
Can anyone help me?
I am percepting that malloc(100*sizeof(char)) will create 100 blocks each of size of character contiguously. Please correct me if I am wrong?
I'll disregard all the fluff about arrays and malloc as it is irrelevant to the problem you describe. You seem to essentially be asking "What will this code print:"
char c = 5;
printf("%c", c);
It will print the symbol 5 in your symbol table, most likely a non-printable character. When encountering non-printable characters, some implementations choose to print non-standard symbols, such as smileys.
If you want to print the number 5, you have to use a character literal:
char c = '5';
printf("%c", c);
or alternatively use poor style with "magic numbers":
char c = 53; // don't write code like this
printf("%c", c);
It is a problem of character representation. Let's begin by the opposite first. A char can be promoted to an int, but if you do you get the representation of the character (its code). Assuming you use ASCII:
char c = '5';
int i = c; // i is now 0x35 or 53 ASCII code for '5'
Your example is the opposite, 5 can be represented by a char, so result[count] = k is defined (even if you should have got a warning for possible truncation), but ASCII char for code 5 is control code ENQ and will be printed as ♣ on a windows system using code page 850 or 437.
A half portable (not specified, but is known to work on all common architectures) way to do the conversion (int) 5 -> (char) '5' is to remember that code '0' to '9' are consecutive (as are 'A' to 'Z' and 'a to 'z'), so I think that what you want is:
result[count] = '0' + k;
First, let's clean up your code a bit:
int k=5;
char* result = malloc(100);
result[count] = k;
sizeof(char) is always equal to 1 under any platform and you don't need to cast the return of malloc() in C.
This said, as long as your count variable contains a value between 0 and 99, you're not doing anything wrong. If you want to print the actual character '5', then you have to assign the ASCII value of that character (53), not just the number 5. Also, remember that if that array of chars has to be interpreted as a string, you need to terminate it with '\0':
int k=5, i;
char* result = malloc(100);
for (i=0; i<98; i++) {
result[i] = ' ';
}
result[98] = 53;
result[99] = '\0';
printf("%s\n", result);
The elements in the array you're trying to allocate are all the size of a char, 1 byte. An int is 4 bytes thus your issues. If you want to store ints in an array you could do:
int result[100];
Followed by storing the value, but honestly from the way your questioned is posed I don't know if that's actually what you're trying to do. Try rephrasing the post with what you're trying to accomplish.
Are you trying to store 5 as a character?
Related
This is probably a very simple solution, but for the life of me I can't figure it out. I'm trying to create a char array (so a char*) consisting of numbers from 0 to numPlayers - 1, which I will iterate through to access whose turn it is. So, if numPlayers = 10, I want gameState.players to be [0,1,2,3,4,5,6,7,8,9]. What did I do wrong?
printf("How many players will be playing: ");
scanf(" %d", &numPlayers);
gameState.players = (char*) malloc(numPlayers * sizeof(char));
for (int i = 0; i < numPlayers; ++i) {
strcpy(gameState.players[i],(char) i);
}
First off:
gameState.players = (char*) malloc(numPlayers * sizeof(char));
The explicit cast is ill-advised in C (it can hide certain subtle errors) and the multiplication by sizeof(char) is never needed - it's always one.
But the real problem lies here:
strcpy(gameState.players[i],(char) i);
The str* functions are meant to work with C strings (null terminated character arrays). You do not have a string, rather you have a character value, so it should be more along the lines of:
gameState.players[i] = i;
You also need to keep in mind:
Though you're using char variables, the value being put in is not the textual representation of the digit. To get that, you would need to use i + '0'(a). Characters are generally meant to be used for (mostly) printable stuff, you would be better off using a more-specific data type like int or unsigned short` for non-character data.
This scheme (assuming you want textual representation) is going to break horribly if you ever use more than ten items.
(a) There's a big difference between the "characters" 7 and '7'. The former actually has the value 7 (ASCII BEL, if you're using ASCII), the latter has the value 0x37 (again, assuming ASCII/Unicode).
The numeric characters are the only ones guaranteed to be consecutive so you can convert a numeric value 0..9 to the printable character value simply by adding '0'.
Please be careful when calling functions, you have to make sure that you are
using the correct types. If you use an incorrect one, the compiler will warn you
or print an error, you should read the warnings and errors of the compiler. They
tell you what is wrong.
strcpy is used to copy strings. The signature of the functions is
char *strcpy(char *dest, const char *src);
it expects a pointer to char as destination, and a pointer to char as the
source. Also strcpy expects a valid C-String. A C-Strings is a sequence of
char bytes that ends with the value '\0'. If you don't have a valid
C-String, you cannot use strcpy.
strcpy(gameState.players[i],(char) i)
Is wrong on many levels:
The arguments are not pointers of char
You are not dealing with valid C-strings
Casting won't help you here, you even did the wrong casting.
1 is not the same as '1'. The character '1' is actually the vakue 49
(ASCII code). If you want to get the ASCII representation of a digit, you have
to do: '0' + digit.
You should do:
for (int i = 0; i < numPlayers; ++i) {
gameState.players[i] = '0' + i;
}
Note that this would only work for max. 9 players. If you need more, then you
have to use an array of strings.
Also note that gameState.players does not point to a C-String, because it is
not '\0'-terminated. You cannot calls strings functions on it. If you want
to do that, then you have to change your code like this:
printf("How many players will be playing: ");
fflush(stdout);
scanf(" %d", &numPlayers);
if(numPlayers > 9)
{
// error, do not continue
}
gameState.players = calloc(numPlayers + 1, sizeof *gameState.players);
for (int i = 0; i < numPlayers; ++i) {
gameState.players[i] = '0' + i;
}
I'm trying to add an int to a char array. My (broken) code is as follows,
string[i] = (char) number;
with i being some int index of the array and number is some integer number. Actually, while typing this out I noticed another problem that would occur if the number is more than one digit, so if you have some answer to that problem as well that would be fantastic!
Given the revised requirement to get digit '0' into string[i] if number == 0, and similarly for values of number between 1 and 9, then you need to add '0' to the number:
assert(number >= 0 && number <= 9);
string[i] = number + '0';
The converse transform is used to convert a digit character back to the corresponding number:
assert(isdigit(c));
int value = c - '0';
If you want to convert a single digit to a number character you can use
string[i] = (char) (number+'0');
Of course you should check if the int value is between 0 and 9. If you have arbitrary numbers and you want to convert them to a string, you should use snprintf, but of course, then you can't squeeze it in a char aynmore, because each char represents a single digit.
If you create the digit representation by doing it manually, you should not forget that a C string requires a \0 byte at the end.
You'll want to use sprintf().
sprintf(string,'%d',number);
I believe.
EDIT: to answer the second part of your question, you're casting an integer to a character, which only holds one digit, as it were. You'd want to put it in a char* or an array of chars.
use asprintf :
char *x;
int size = asprintf(&x, "%d", number);
free(x);
is better because you don't have to allocate memory. is done by asprintf
I am trying to store an integer in a char array. How can I do that? This is my approach (by casting it the int to a char) but it does not work. What am I missing?
#include <stdio.h>
int main(int argc, char** argv)
{
char cArray[10] = {};
// Store a character in the char array
cArray[5] = 'c';
printf("%c\n", cArray[5]);
// Store an integer in the char array
cArray[6] = (char) 0; // WHY DOES THIS NOT WORK???
printf("%c\n", cArray[6]);
}
Let's start with the basics.
For x86 architecture(assuming you use it) a char variable is stored in 1 byte and an int variable is stored in 4 bytes.
It is IMPOSSIBLE to store a random integer value in a char variable unless you have some compression schema and know that some integer values will not occur(no random!) in your program. No exceptions.
In your case, you want to store integers in a char array. There are four options:
1.If you want to store a random integer in this char array, then you should get the pointer to the index that you want to store the integer and cast it to an integer pointer and use it like that.
char mychars[10];
int * intlocation = (int*)(&mychar[5]);
*intlocation = 3632; // stores 3632
Beware that this will write to 4 bytes(4 char locations in your array) starting from the index you have specified. You should always check you are not going out of array.Also you should do the same casting for retrieving the value when needed.
2.If your values are between [0,255] or [-128,127] you can safely store your integers in a char since these ranges can be represented using a byte. Beware that char being signed or unsigned is implementation-dependent. Check this out!
mychars[5] = 54;
3.If your integer is just a digit, you can use the char representation of the digit.
mychars[5] = your_digit + 48; // 48 is the ascii code for '0'
4.If you want to store the string representation of your integer, then you should use itoa() and write each char of the resulting string to your array one by one. In that case, you should always check that you are not going out of array.
cArray[6] = (char) 0; // WHY DOES THIS NOT WORK???
printf("%c\n", cArray[6]);
This code attempts to print a character with the encoding 0; assuming ASCII, nothing will get displayed because there is no printable character associated with that code.
If you intend to store the ASCII code for the character '0' and print it, then you need to write
cArray[6] = 48; // same as writing cArray[6] = '0' (ASCII)
printf( "%c\n", cArray[6] );
This will print 0 to your console.
If, on the other hand, you want to store any arbitrary integer value1 to cArray[6] and display that value, then you need to use the %d conversion specifier:
cArray[6];
printf( "%d\n", cArray[6] );
1. That is, any integer that fits into the range of char, anyway
Normally, a computer exactly does what you tell it. The instruction DWIM (do what I mean) hasn't been invented yet.
cArray[6] = (char) 0; // WHY DOES THIS NOT WORK???
sets the index position 6, but
printf("%c\n", cArray[5]);
prints the index position 5.
I would like to add on to Seçkin Savaşçı's answer (in which you cast a char* pointer to somewhere in the char array to an int* pointer, allowing you to write an integer to the array by dereferencing the pointer).
You can also use bit-shifting:
#include <stdio.h>
int main() {
int first_int = 4892; // number larger than 127 (max. value of char)
int second_int = 99584; // same
// char array to hold two integers:
char array[8]; // ...assuming an integer size of 4 and char size of 1
// Now, assuming you are on a little endian system (in which the least
// significant bytes come first), you can add the two above integers to the
// array like so:
array[0] = first_int; // assigns first_int's least significant byte
array[1] = first_int >> 8; // assigns first_int's 2nd least significant byte
array[2] = first_int >> 16; // assigns first_int's 2nd most significant byte
array[3] = first_int >> 24; // assigns first_int's most significant byte
// repeat for second_int:
array[4] = second_int;
array[5] = second_int >> 8;
array[6] = second_int >> 16;
array[7] = second_int >> 24;
// You can now prove that this char array holds the two integers like this:
printf("First integer: %d\n", *((int *) array));
printf("Second integer: %d\n", *((int *) (array + 4)));
return 0;
}
On a big endian system you would first assign the most significant byte, and move on to the least significant bytes.
Replace
cArray[6] = (char) 0; // WHY DOES THIS NOT WORK???
printf("%c\n", cArray[5]);
By
cArray[6] = (char)51;
printf("%c\n", cArray[6]);
Should display '3'
I think you will understand your mistake... 0 as int does not represent the printable character '0', but the NULL termination string
51 as int represent the character '3'
You may use itoa(0,&cArry[6],10).
Use the correctly desired format specifier.
cArray[6] = (char) 0; does store an integer 0 into array element cArray[6]. Its the printf() that is fooling OP into thinking that did not work.
Using %c says OP wants the character that is encoded with a 0. (It usually not visible). Use %d to print the integer value of cArray[6].
printf("%d\n", cArray[6]);
You can add the ASCII value of 0 to the value you want to store digit into the character array.
For example if you want to store 0,1,...,9 into the character array A[10], you may use the following code.
for(j = 0; j<k; j++)
{
A[j] = j + '0'; // Same effect if you use A[j] = j + 0x30
}
This works only if the integer you want to store is less than 10. Otherwise you will have to extract the digits using modulo operator and store.
I am new to c programming. As a part of my uni course for network security, I have to design a SSL handshake simulation. I found a sample code online, however i don't understand some parts of the code. Could you please help me with following :
What does (char) 0 do ?? ( send_data is defined as char send_data[1024]; )
send_data[0] = (char) 0; //Packet Type = hello
send_data[1] = (char) 3; //Version
EDIT + FOLLOWUP
Folks I know what type casting is.
I understand what casting is But the code I posted is doing nothing. Even though integer 0 is being cast as a character, its not doing anything because when you print it - its a blank - no value.
eg :
#include <stdio.h>
#include <stdlib.h>
int main(){
char test;
int num;
num = 1;
test = (char) num; // this does nothing
printf("num = %d , %c\n",num,num);
printf("test = %d , %c\n",test,test);
// Isn't this the correct way to do it ?? :
num = 3;
test = '3'; // now this is a character 3
printf("num = %d , %c\n",num,num);
printf("test = %d , %c\n",test,test);
return 0;
}
the output of above code is :
num = 1 ,
test = 1 ,
num = 3 ,
test = 51 , 3
So why is it being done ?? isn't this the right way to do it :- send_data[0] = '0'; send_data[1] = '3';
It simply casts the int 0 (or 3) into a char type.
It's possibly not necessary but may be used to remove warnings of possible truncation.
A better idiom would be:
send_data[0] = '\x00'; // Packet Type = hello
send_data[1] = '\x03'; // Version
since those are explicitly characters, without having to worry about casting.
Keep in mind that (char) 0 (or '\x00') is not the same as '0'. The former two give you the character code 0 (the NUL character in ASCII), the latter gives you the character code for the printable 0 character (character code 48 or '\x30' in ASCII). That's why your printing isn't acting as you seem to expect.
Whether your particular protocol requires code point 0 or printable character 0 is something you haven't made clear. If you're truly trying to emulate SSLv3, the correct values are the binary rather than printable ones as per RFC6101:
enum {
hello_request(0), client_hello(1), server_hello(2),
certificate(11), server_key_exchange (12),
certificate_request(13), server_done(14),
certificate_verify(15), client_key_exchange(16),
finished(20), (255)
} HandshakeType;
It is just casting the literal symbol into a char value. But I don't think it is necessary.
It is casting the int value into the char type.
This is known as type-conversion or casting. You do this when you need to change an entity of one data-type to another.
In your examples, 0 and 3 (integers) are being casted as type chars.
http://en.wikipedia.org/wiki/Type_conversion
send_data is defined as an array of char. But 0 and 3 are integer literals. When the integers are assigned to the array, they are being cast as char. This means that send_data [0] will hold the character with ASCII value 0, i.e. the NUL character. send_data[1] will hold the character with ASCII value 3, the end of text character.
int main()
{
char ch;
ch = (char) 0;
printf("%d\n", ch); //This will print 0
printf("%c\n", ch); //This will print nothing (character whose value is 0 which is NUL)
ch = (char) 3;
printf("%d\n", ch); //This will print 3
printf("%c\n", ch); //This will print a character whose value is 3
return 0;
}
It is type casting int type to char type.
Its good to create a demo program and test it when you get some doubts while reading.
been searching everywhere, but couldn't the correct answer.
the problem is pretty simple:
i have to convert ASCII integer values into char's.
for example, according to ASCII table, 108 stands for 'h' char. But when i try to convert it like this:
int i = 108
char x = i
and when I printf it, it shows me 's', no matter what number i type in(94,111...).
i tried this as well:
int i = 108;
char x = i + '0'
but i get the same problem! by the way, i have no problem in converting chars into integers, so i don't get where's the problem :/
thanks in advance
That is how you do it. You probably want it unsigned, though.
Maybe your printf is wrong?
The following is an example of it working:
// Print a to z.
int i;
for (i = 97; i <= 122; i++) {
unsigned char x = i;
printf("%c", x);
}
This prints abcdefghijklmnopqrstuvwxyz as expected. (See it at ideone)
Note, you could just as well printf("%c", i); directly; char is simply a smaller integer type.
If you're trying to do printf("%s", x);, note that this is not correct. %s means print as string, however a character is not a string.
If you do this, it'll treat the value of x as a memory address and start reading a string from there until it hits a \0. If this merely resulted in printing s, you're lucky. You're more likely to end up getting a segmentation fault doing this, as you'll end up accessing some memory that is most likely not yours. (And almost surely not what you want.)
Sounds to me like your printf statement is incorrect.
Doing printf("%c", c) where c has the value 108 will print the letter l... If you look at http://www.asciitable.com/ you'll see that 108 is not h ;)
I'm guessing your printf statement looks like this:
printf("s", x);
..when in fact you probably meant:
printf("%s", x);
...which is still wrong; this is expecting a string of characters e.g:
char* x = "Testing";
printf("%s", x);
What you really want is this:
int i = 108;
char x = i + '0';
printf("%c", x);
...which on my system outputs £