Questions about a Kernighan and Ritchie Excercise 2-3 - c

I'm trying to write a program in C that converts hexadecimal numbers to integers. I've written successfully a program that converts octals to integers. However, the problems begin once I start using the letters (a-f). My idea for the program is ads follows:
The parameter must be a string that starts with 0x or 0X.
The parameter hexadecimal number is stored in a char string s[].
The integer n is initialized to 0 and then converted as per the rules.
My code is as follows (I've only read up to p37 of K & R so don't know much about pointers) :
/*Write a function htoi(s), which converts a string of hexadecimal digits (including an optional 0x or 0X) into its equivalent integer value. The allowable digits are 0 through 9, a through f, and A through F.*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
int htoi(const char s[]) { //why do I need this to be constant??
int i;
int n = 0;
int l = strlen(s);
while (s[i] != '\0') {
if ((s[0] == '0' && s[1] == 'X') || (s[0] == '0' && s[1] == 'x')) {
for (i = 2; i < (l - 1); ++i) {
if (isdigit(s[i])) {
n += (s[i] - '0') * pow(16, l - i - 1);
} else if ((s[i] == 'a') || (s[i] == 'A')) {
n += 10 * pow(16, l - i - 1);
} else if ((s[i] == 'b') || (s[i] == 'B')) {
n += 11 * pow(16, l - i - 1);
} else if ((s[i] == 'c') || (s[i] == 'C')) {
n += 12 * pow(16, l - i - 1);
} else if ((s[i] == 'd') || (s[i] == 'D')) {
n += 13 * pow(16, l - i - 1);
} else if ((s[i] == 'e') || (s[i] == 'E')) {
n += 14 * pow(16, l - i - 1);
} else if ((s[i] == 'f') || (s[i] == 'F')) {
n += 15 * pow(16, l - i - 1);
} else {
;
}
}
}
}
return n;
}
int main(void) {
int a = htoi("0x66");
printf("%d\n", a);
int b = htoi("0x5A55");
printf("%d\n", b);
int c = htoi("0x1CA");
printf("%d\n", c);
int d = htoi("0x1ca");
printf("%d\n", d);
}
My questions are:
1. If I don't use const in the argument for htoi(s), i get the following warnings from the g++ compiler :
2-3.c: In function ‘int main()’: 2-3.c:93:20: warning: deprecated
conversion from string constant to ‘char*’ [-Wwrite-strings]
2-3.c:97:22: warning: deprecated conversion from string constant to
‘char*’ [-Wwrite-strings] 2-3.c:101:21: warning: deprecated conversion
from string constant to ‘char*’ [-Wwrite-strings] 2-3.c:105:21:
warning: deprecated conversion from string constant to ‘char*’
[-Wwrite-strings]
Why is this?
2.Why is my program taking so much time to run? I haven't seen the results yet.
3.Why is it that when I type in cc 2-3.c instead of g++ 2-3.c in the terminal, I get the following error message:
"undefined reference to `pow'"
on every line that I've used the power function?
4. Please do point out other errors/ potential improvements in my program.

If I don't use const in the argument for htoi(s), i get the following warnings from the g++ compiler
The const parameter should be there, because it is regarded as good and proper programming to never typecast away const from a pointer. String literals "..." should be treated as constants, so if you don't have const as parameter, the compiler thinks you are casting away the const qualifier.
Furthermore, you should declare all pointer parameters that you don't intend to modify the contents of as const, Google the term const correctness.
Why is my program taking so much time to run? I haven't seen the results yet.
I think mainly because you have made an initialization goof-up. int i; i contains rubbish. Then while (s[rubbish_value] != '\0'). This function can be written a whole lot better too. Start by checking for the 0x in the start of the string, if they aren't there, signal some error (return NULL?), otherwise discard them. Then start one single loop after that, you don't need 2 loops.
Note that the pow() function deals with float numbers, which will make your program a slight bit slower. You could consider using an integer-only version. Unfortunately there is no such function in standard C, so you will have to found one elsewhere.
Also consider the function isxdigit(), a standard function in ctype.h, which checks for digits 0-9 as well as hex letters A-F or a-f. It may however not help with performance, as you will need to perform different calculations for digits and letters.
For what it is worth, here is a snippet showing how you can convert a single char to a hexadecimal int. It is not the most optimized version possible, but it takes advantage of available standard functions, for increased readability and portability:
#include <ctype.h>
uint8_t hexchar_to_int (char ch)
{
uint8_t result;
if(isdigit(ch))
{
result = ch - '0';
}
else if (isxdigit(ch))
{
result = toupper(ch) - 'A' + 0xA;
}
else
{
// error
}
return result;
}

Don't use a C++ compiler to compile a C program. That's my first advice to you.
Secondly const in a function parameter for a char * ensures that the programmer doesn't accidentally modify the string.
Thirdly you need to include the math library with -lm as stated above.

a const char[] means that you cannot change it in the function. Casting from a const to not-const gives a warning. There is much to be said about const. Check out its Wikipedia page.
--
Probably, cc doesn't link the right libraries. Try the following build command: cc 2-3.c -lm
Improvements:
Don't use pow(), it is quite expensive in terms of processing time.
Use the same trick with the letters as you do with the numbers to get the value, instead of using fixed 'magic' numbers.
You don't need the last else part. Just leave it empty (or put an error message there, because those characters aren't allowed).
Good luck!
About my remark about the pow() call (with the use of the hexchar_to_int() function described above, this is how I'd implement this (without error checking):
const char *t = "0x12ab";
int i = 0, n = 0;
int result = 0;
for (i = 2; i < strlen(t); i++) {
n = hexchar_to_int(t[i]);
result |= n;
result <<= 4;
}
/* undo the last shift */
result >>= 4;

I just worked through this exercise myself, and I think one of the main ideas was to use the knowledge that chars can be compared as integers (they talk about this in chapter 2).
Here's my function for reference. Thought it may be useful as the book doesn't contain answers to exercises.
int htoi(char s[]) {
int i = 0;
if(s[i] == '0') {
++i;
if(s[i] == 'x' || s[i] == 'X') {
++i;
}
}
int val = 0;
while (s[i] != '\0') {
val = 16 * val;
if (s[i] >= '0' && s[i] <= '9')
val += (s[i] - '0');
else if (s[i] >= 'A' && s[i] <= 'F')
val += (s[i] - 'A') + 10;
else if (s[i] >= 'a' && s[i] <= 'f')
val += (s[i] - 'a') + 10;
else {
printf("Error: number supplied not valid hexadecimal.\n");
return -1;
}
++i;
}
return val;
}

Always init your variables int i=0, otherwise i will contain a garbage value, could be any number, not necessary 0 as you expect. You're running the while statement in an infinite loop, that's why it takes forever to get the results, print i to see why. Also, add a break if the string doesn't start with 0x, will avoid the same loop issue when the user is used on a random string. As others mention you need to import the library containing pow function and declare your string with const to get rid of the warning.

This is my version of program for the question above. It converts the string of hex into decimal digits irrespective of optional prefix(0x or 0X).
4 important library functions used are strlen(s), isdigit(c), isupper(c), isxdigit(c), pow(m,n)
Suggestions to improve the code are welcome :)
/*Program - 5d Function that converts hex(s)into dec -*/
#include<stdio.h>
#include<stdlib.h>
#include<math.h> //Declares mathematical functions and macros
#include<string.h> //Refer appendix in Page 249 (very useful)
#define HEX_LIMIT 10
int hex_to_dec(char hex[]) //Function created by me :)
{
int dec = 0; //Initialization of decimal value
int size = strlen(hex); //To find the size of hex array
int temp = size-1 ; //Pointer pointing the right element in array
int loop_limit = 0; //To exclude '0x' or 'OX' prefix in input
if(hex[0]=='0' && ((hex[1]=='x') || (hex[1]=='X')))
loop_limit = 2;
while(temp>=loop_limit)
{
int hex_value = 0; //Temporary value to hold the equivalent hex digit in decimal
if(isdigit(hex[temp]))
hex_value = (hex[(temp)]-'0') ;
else if(isxdigit(hex[temp]))
hex_value = (toupper(hex[temp])-'A' + 10);
else{
printf("Error: No supplied is not a valid hex\n\n");
return -1;
}
dec += hex_value * pow(16,(size-temp-1)); //Computes equivalent dec from hex
temp--; //Moves the pointer to the left of the array
}
return dec;
}
int main()
{
char hex[HEX_LIMIT];
printf("Enter the hex no you want to convert: ");
scanf("%s",hex);
printf("Converted no in decimal: %d\n", hex_to_dec(hex));
return 0;
}

Related

Problems with sums of chars in C

I'm very new to C so I'll make it quick: I'm making a Caesar's Cipher but at some point it starts giving me ? symbols.
#include <stdio.h>
#include <ctype.h>
int main(void){
char c;
int k;
printf("Inserisci la chiave di cifratura: ");
scanf("%d", &k);
if (k > 26)
k = (k%26);
printf("%d", k);
while ((c=getchar()) != '.') {
if (isalpha(c)) {
if (c >= 'a' && c <= 'z') {
c = c + k;
if (c > 'z') {
c = c - 'z' + 'a' - 1;
}
}
else if (c >= 'A' && c <= 'Z') {
c = c + k;
if (c > 'Z') {
c = c - 'Z' + 'A' - 1;
}
}
putchar(c);
}
else
putchar(c);
}
printf("\n");
return 0;
}
If k is 6, it starts giving me the symbol with z.
If it is 7, it start with y.
Etc...
I can't find anything around, thank you to whoever helps me.
When you use char, it's implementation-defined whether it's treated as signed char or unsigned char. Your implementation apparently defaults to signed char. The value of 'z' is 122, and when you add 6 to this you get 128, which overflows and causes undefined behavior. The maximum value of signed char is 127.
You should declare c to be int or unsigned char.
Your solution ensures the offset k is in the range of 0 through 26. You can get the correct solution if your offset is in the range of 0 through 25. An offset of 26 should produce the same results as an offset of 0.
When calculating the offset character you simply add K and then try to use addition to adjust for values greater than 'z' or 'Z'. You can adjust the value without the use of another set of conditional statements using the modulus operator.
Since this appears to be a homework problem I have created a solution in Ada rather than C. You can translate the logic into C.
with Ada.Text_Io; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Main is
subtype Offset is Natural range 0..25;
K : Offset;
C : Character := ' ';
Code : Natural;
adjusted : Character;
begin
Put("Enter the letter shift amount: ");
Get(K);
Put_Line("Specified offset is" & K'Image);
while C /= '.' loop
Get(C);
if C in 'a'..'z' then
Code := (Character'Pos(C) - Character'Pos('a') + k) mod 26;
adjusted := Character'Val(Code + Character'Pos('a'));
Put(adjusted);
elsif C in 'A'..'Z' then
Code := (Character'Pos(C) - Character'Pos('A') + k) mod 26;
adjusted := Character'Val(Code + Character'Pos('A'));
Put(adjusted);
else
Put(C);
end if;
end loop;
end Main;
Ada does not allow arithmetic directly on characters. Instead it allows arithmetic on the "position" of the character, which is a numeric value. The function Character'Pos(C) returns the numeric position of the character stored in variable C. The function Character'Val() returns the character corresponding to a specified numeric value.

Can we set a variable to a number range in C?

What I'm thinking of is something like this:
range = range <= '9' && range >= '0';
I want to extract a contiguous sequence of digits from a string. And once the program find a non-digit after it finds the sequence of digits, I want it to break out of the loop using break; in the second if-statement (line 59). And I think it would be much easier if I can just write the condition using a variable.
What I want to say in line 59 is "If the var digit_flag is TRUE and the element in the array s is included in the var range(which is a number range), then break;"
Can it be done?
If it can't, why not?
int i = 0;
int size_of_s = 0;
int digit_flag = FALSE;
while (s[i] != '\0') {
if (s[i] == ' ') {
i++;
} else if (s[i] <= '9' && s[i] >= '0') {
size_of_s++;
i++;
digit_flag = TRUE;
}
if (digit_flag == TRUE && s[i] != range) {
break;
}
}
What I want to say in line 59 is "If the var digit_flag is TRUE and the element in the array s is included in the var range(which is a number range), then break;"
Can it be done?
As far as I know this can not be done in C.
If it can't, why not?
Because there is no relational or comparison operator in the C language which means "operand 1 is within the range of operand 2" (even if the second operand is an array). You need to use a logical AND (&&) of two conditions (>= A, <= B).
If you don't want to use a standard function - such as isdigit(), which will use the range 0-9 - you could use a macro
#define IS_IN_RANGE(x, min, max) (x >= min && x <= max)
or inline function.
static inline int is_in_range(int x, int min, int max) {
return (x >= min && x <= max);
}
If you want a "range" in C, you have to create one yourself:
// integer range class
// in this case it could also be a char range
struct int_range {
int start;
int end;
};
// range method to test for inclusinon
// in this case range could be passed as value efficiently, too,
// but passing as const pointer is more generic, so better example
bool int_range_contains(const struct int_range *range, int value) {
return value >= range->start && value <= range->end;
}
// example usage
void func(void) {
struct range digit_chars = { '0', '9' };
int character = 'a';
if (int_range_contains(&digit_chars, character)) {
// something
}
}
Of course this is a total overkill for this case. Your current if (s[i] <= '9' && s[i] >= '0') is better, and every C programmer immediately sees what's going on there.
Instead of
digit_flag == TRUE && s[i] != range
you can re-use what you already wrote
digit_flag == TRUE && !(s[i] <= '9' && s[i] >= '0')
If you want to extract the number sequence part in a string like
char str[]="hello1234isthesequence.";
you could just do
char seq[30];
if( sscanf(str, "%*[^0-9]%[0-9]", seq)==1 )
{
printf("\nThe sequence is: %s", seq);
}
where the %*[^0-9] is used to read everything from str[] till a non-digit character is encountered and the * is to suppress it ie, it will be discarded and won't be assigned to anywhere.
Next the %[0-9] will read the remaining part of the string in str till and excluding non-number and assign it to seq.
sscanf() will return the number of total successful assignments that it made, which in this case should be 1.
You may change the size of seq as per the size of the input string and change the width specifier in the format string of scanf() to avoid overflow.

Decimal to Binary in C

I'm creating a program that adds and subtracts 2 numbers. Then I have to output this answer into different bases.
My answer is in decimal format, of type long double, such as:
long double answer;
answer = numberOne + numberTwo;
I want to convert this answer into binary. Now I have code used earlier in my program that does this, but with a char pointer:
char * decimalBinary (char * decimalNumber)
{
bool zeroFront = true;
int i;
int z;
int j = 0;
int n = atoi(decimalNumber);
char * binaryNum = malloc(32+1);
binaryNum[32] = '\0';
int current_index=1;
int end_index = strlen(decimalNumber)-1;
//Error check for valid decimal input, needed error check for beginning of code
while(current_index <= end_index)
{
if(decimalNumber[current_index] != '0' &&decimalNumber[current_index] != '1' &&decimalNumber[current_index] != '2' &&decimalNumber[current_index] != '3' &&decimalNumber[current_index] != '4' &&decimalNumber[current_index] != '5' &&dec[current_index] != '6' &&dec[current_index] != '7' &&decimalNumber[current_index] != '8' &&decimalNumber[current_index] != '9')
{
binaryNum[0] = -8;
return binaryNum;
}
current_index++;
}
for (i = 31; i >= 0; i--) {
z = n >> i;
if (z & 1)
{
binaryNum[j] = '1';
j++;
zeroFront = false;
}
else if (!zeroFront)
{
binaryNum[j] = '0';
j++;
}
}
binaryNum[j] = '\0';
return binaryNum;
}
My preferred solution is to use the code I already have in my program to convert my answer into a binary format, but as you can see the parameters are conflicting, and I'm not sure how to go about doing that.
Another possible solution that detracts from having reusable code in my program, is to create a different function all together that converts a decimal to a binary, but accepting a parameter of type long double, which is a bit unclear to me as well.
Edit:
Instead of long double, my answer is of type int.
If you really want to reuse your function without modifications, you can transform answer into a decimal string and pass the string to your function.
char stringAnswer[20];
sprintf(stringAnswer, "%d", answer);
printf("the binary answer is %s\n", decimalBinary(stringAnswer));
But a better solution should be to split the function decimalBinary into two functions : the first one to check that all digits are ok, and the second one to convert a int into a binary string.
Then you'll be able to call directly this second function with answer as parameter.
Rather than use a magic number 32, better to let the compiler deduce the needed size as an int is not always 32 bits. Checking allocation results is a good habit.
#include <assert.h>
#include <stdlib.h>
#define INT_MAX_BIN_WIDTH (sizeof(int) * CHAR_BIT)
char * binaryNum = malloc(INT_MAX_BIN_WIDTH+1);
assert(binaryNum != NULL);
binaryNum[INT_MAX_BIN_WIDTH] = '\0'; // null character
Rather than checking against each digit, since '0' to '9' must be sequential:
// if(decimalNumber[current_index] != '0' &&decimalNumber[current_index] != '1' ...
if (decimalNumber[current_index] < '0' || decimalNumber[current_index] >= '9') ...
// or
if (!isdigit((unsigned char) decimalNumber[current_index])) ...
Problem does not address negative numbers. Better to state that they will not occur or better, make code handle them.
Code allocates memory, but does not free it. Consider letting the higher level code allocate/free and supply the needed buffer to decimalBinary(char *dest, size_t size, const char *src). Robust code would supply the size too.
char *binaryNum = malloc(INT_MAX_BIN_WIDTH+1);
assert(binaryNum != NULL);
decimalBinary(binaryNum, INT_MAX_BIN_WIDTH+1, "123");
do_something(binaryNum);
free(binaryNum);
Following is a solution that is not limited to 32 bits. It does not cope with negative numbers nor memory allocation - certainly it should provide some ideas for your eventual solution.
#include <stdio.h>
#include <string.h>
static void times10(char *binaryNumber, int carry) {
size_t length = strlen(binaryNumber);
size_t i = length;
while (i > 0) {
i--;
int sum = (binaryNumber[i] - '0') * 10 + carry;
binaryNumber[i] = sum % 2 + '0';
carry = sum / 2;
}
while (carry) {
memmove(&binaryNumber[1], &binaryNumber[0], ++length);
binaryNumber[0] = carry % 2 + '0';
carry /= 2;
}
}
char *decimalBinary(char *binaryNumber, const char *decimalNumber) {
strcpy(binaryNumber, "0");
int ch;
while ((ch = *decimalNumber++) >= '0' && (ch <= '9')) {
times10(binaryNumber, ch - '0');
}
return binaryNumber;
}
int main(void) {
char buf10[200];
puts(decimalBinary(buf10, "123"));
puts(decimalBinary(buf10, "123456"));
puts(decimalBinary(buf10, "123456789012345678901234567890"));
return 0;
}

best way to check if is digit in specific base in C

I know that ctype.h defines isdigit, however this only works for base 10. I'd like to check to see if a number is a digit in a given base int b.
What's the best way to do this in C?
Edit
I've come up with the following function:
int y_isdigit(char c, int b) {
static char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static int digitslen = sizeof digits - 1;
static int lowest = 0;
int highest = b - 1;
if(highest >= digitslen)
return -1; /* can't handle bases above 35 */
if(b < 1)
return -2; /* can't handle bases below unary */
if(b == 1)
return c == '1'; /* special case */
int loc = strchr(digits, c);
return loc >= lowest && loc <= highest;
}
Is there any advantage to using the version schnaader made to this? (This seems to have the added benefit of not relying on the user's charset being ASCII—not that it matters much anymore.)
I'd suggest something like this:
// input: char c
if (b <= 10) {
if ((c >= '0') && (c < ('0' + b))) {
// is digit
}
} else if (b <= 36) {
if ((c >= '0') && (c <= '9')) {
// is digit
} else if ((c >= 'A') && (c < 'A' + (b - 10))) {
// is digit
}
}
This should work (untested) for base 2..36 if you're using 0..9 and A..Z.
An alternative would be to use a boolean lookup table, this is the fastest way to check. For example you could prepare tables for bases 2..36, using up 256*35 = 8960 bytes of memory, after this the isdigit check is a simple memory read.
if you are using conventional bases (e.g. octal or hexadecimal) you can use strtol() to convert and check for an error condition. if you are using arbitrary bases, e.g. base 99 there may not be an out of the box solution.
The advantage of isdigit is that it is usually a macro that expands at compile time. There is also another one isxdigit.
If you'd want to do the same for your own convention of digits you could go for an inline function that would be almost as good:
inline
bool isdigit42(char c) {
switch (c) {
default: return false;
case '0': return true;
case '1': return true;
.
.
}
}
Your compiler would know best of what cases can be shortened because the characters are in a common range of values. And in case that this is called with a compile time constant character this should be completely optimized out.

Parsing Integer to String C

How does one parse an integer to string(char* || char[]) in C? Is there an equivalent to the Integer.parseInt(String) method from Java in C?
If you want to convert an integer to string, try the function snprintf().
If you want to convert a string to an integer, try the function sscanf() or atoi() or atol().
To convert an int to a string:
int x = -5;
char buffer[50];
sprintf( buffer, "%d", x );
You can also do it for doubles:
double d = 3.1415;
sprintf( buffer, "%f", d );
To convert a string to an int:
int x = atoi("-43");
See http://www.acm.uiuc.edu/webmonkeys/book/c_guide/ for the documentation of these functions.
It sounds like you have a string and want to convert it to an integer, judging by the mention of parseInt, though it's not quite clear from the question...
To do this, use strtol. This function is marginally more complicated than atoi, but in return it provides a clearer indication of error conditions, because it can fill in a pointer (that the caller provides) with the address of the first character that got it confused. The caller can then examine the offending character and decide whether the string was valid or not. atoi, by contrast, just returns 0 if it got lost, which isn't always helpful -- though if you're happy with this behaviour then you might as well use it.
An example use of strtol follows. The check for error is very simple: if the first unrecognised character wasn't the '\x0' that ends the string, then the string is considered not to contain a valid int.
int ParseInt(const char *s,int *i)
{
char *ep;
long l;
l=strtol(s,&ep,0);
if(*ep!=0)
return 0;
*i=(int)l;
return 1;
}
This function fills in *i with the integer and returns 1, if the string contained a valid integer. Otherwise, it returns 0.
This is discussed in Steve Summit's C FAQs.
The Java parseInt() function parses a string to return an integer. An equivalent C function is atoi(). However, this doesn't seem to match the first part of your question. Do you want to convert from an integer to a string, or from a string to an integer?
You can also check out the atoi() function (ascii to integer) and it's relatives, atol and atoll, etc.
Also, there are functions that do the reverse as well, namely itoa() and co.
You may want to take a look at the compliant solution on this site.
You can try:
int intval;
String stringval;
//assign a value to intval here.
stringval = String(intval);
that should do the trick.
This is not an optimal solution. This is my solution given multiple restrictions, so if you had limited resources based on your course/instructor's guidelines, this may be a good fit for you.
Also note that this is a fraction of my own project implement, and I had to read in operands as well as digits, so I used getchars. Otherwise, if you only need integers and no other type of characters, I like using this:
int k;
while (scanf("%d", &k) == 1)
The rules were no specific, "advanced" C concepts: no String variables, no structs, no pointers, no methods not covered, and the only include we were allowed was #include
So with no simple method calls like atoi() available or any String variables to use, I chose to just brute force it.
1: read chars in using getchar (fgets was banned). return 1 (exit status 1) if
there is an invalid character. For your problem based of parseInt in Java
1 11 13 is valid but 1 11 1a is invalid, so for all values we have a valid "string" iff all chars are 0-9 ignoring whitespace.
2: convert the ASCII value of a char to its integer value (eg. 48 => 0)
3: use a variable val to store an int such that for each char in a "substring" there is a corresponding integer digit. i.e. "1234" => 1234 append this to an int array and set val to 0 for reuse.
The following code demonstrates this algorithm:
int main() {
int i, c;
int size = 0;
int arr[10]; //max number of ints yours may differ
int val = 0;
int chars[1200]; //arbitrary size to fit largest "String"
int len = 0;
//Part 1: read in valid integer chars from stdin
while((c = getchar()) != EOF && (c < 58 && c > 47)) {
chars[len] = c;
len++;
}
//Part 2: Convert atoi manually. concat digits of multi digit integers and
// append to an int[]
for(i = 0; i < len; i++){
for(i = 0; i < len; i++){
if(chars[i] > 47 && chars[i] < 58){
while((chars[i] > 47 && chars[i] < 58)){
if(chars[i] == 48)
c = 0;
if(chars[i] == 49)
c = 1;
if(chars[i] == 50)
c = 2;
if(chars[i] == 51)
c = 3;
if(chars[i] == 52)
c = 4;
if(chars[i] == 53)
c = 5;
if(chars[i] == 54)
c = 6;
if(chars[i] == 55)
c = 7;
if(chars[i] ==56)
c = 8;
if(chars[i] == 57)
c = 9;
val = val*10 + c;
i++;
}
arr[size] = val;
size++;
if(size > 10) //we have a check to ensure size stays in bounds
return 1;
val = 0;
}
//Print: We'll make it a clean, organized "toString" representation
printf("[");
for(i = 0; i < size-1; i++){
printf("%d, ", arr[i]);
}
printf("%d]", arr[i];
return 0;
Again, this is the brute force method, but in cases like mine where you can't use the method concepts people use professionally or various C99 implements, this may be what you are looking for.

Resources