Hi to everyone. I have a couple of question if anyone help i appreciate so much.
First i am converting char array to int variable. How can i understand the converting is true not overflowed.
Second consider i have a char[20] and half of it are full and i want to resize my array as 30 when i am doing that, array must keep the characters in it.
Thanks...
1) If no overflow occurs, the convertion char->int and then int->char should give the initial value.
2) In C, realloc() function may help you.
Generally speaking, you must allocate memory for 30 elements, copy your old 20 elements to it and free memory occupied by your old 20 elem-s. STL containers std::vector, std::string have appropriate method resize() for the purpose.
thanks for your answer melkiy
overflow will happen during convertion how can i understand that and print "an overflow occured". When overflow occurs, i looked at with debugging in Visual Studio, int variable is happening large number but not same with the content of char array.
and
Can i do that let me explain with an example.
for example i have, char numbers[10]; and i will give some numbers to this array with scanf("%s",numbers); user entered more than 10 numbers. How can understand how many character user entered before scanf's assigning to the numbers array?
> How can understand how many character user entered before scanf's assigning to the numbers array?
There is no common way to do that. But what for? Read the whole user's input, then look how long it is. Use safe version of the function
scanf_s(10, "%s", numbers);
to prevent overflow of the buffer. But you'd rather simply prepare large buffer, 50 additional bytes won't play a key role: char numbers[60];
Then, when you have the user's input in the buffer, use strlen() to find its length.
If i understand well, you are afraid of if user input a larger string like "1234567890987654321" then conversion to integer would fail. As I said above, use the trick of double convertion:
1 2 3 4 5 6 7 8
char str1[30] = "1234567890987654321";
char str2[30];
int num=0;
num = atoi(str); //conversion char* to int
sprintf(str2, "%d", num); //conversion backwards int to char*
if( strcmp(str1, str2) != 0)
printf("Conversion failed!\n");