February 19th, 2003, 03:07 AM
I am reading in a file using getc using this while loop:
while( ((ch = getc(fileIn)) != EOF) && (ch != ']') )
ch is defined as an integer(to avoid problems with conversion from integer->char->integer). My problem is that later in the loop, I use atoi(ch) which wants a pointer to a char. If I cast ch to a pointer inside atoi -> atoi( (char *)ch ), I recieve a segmentation fault. However if I remove explicit casting -> atoi(&ch), I recieve a warning from the compiler, but I recieve no segmentation fault(on my machine at least). How do I remedy this problem?
Thanks in advance.
Last edited by cel; February 19th, 2003 at 03:31 AM.
February 19th, 2003, 11:25 AM
OK, real quickly. atoi() is expecting a character string, an array of characters. Character strings in C are null-terminated, which means that they end with '\0', AKA "null" which has an ASCII value of zero. The need for the null-termination is why you always need to allocation one extra character for your strings.
atoi() scans the string until it reaches a null (or a non-digit character, I believe). If it doesn't encounter one, then it just keeps on going, which could take it outside its memory segment, hence your segmentation error.
(I'm composing this on-line and so I cannot refer back to your message) I believe you tried casting your character value to a character pointer, which has it interpreted as an address which undoubtedly points outside its memory segment, which would again lead to a segmentation error.
Here's a suggestion:
The ASCII values for '0' through '9' are 48 through 57 decimal or 0x30 through 0x39. Subtracting 48 from the character will give you its value. Also, ANDing 0x0F to the character will also give you its value:
int_val = ch - 48;
int_val = ch & 0x0F;
Hope that helps.
February 19th, 2003, 11:59 AM
Thanks for your help, dwise1_aol. I don not know why I did not think of that. (Actually ch is a integer, so I need to AND 0x0000000F to ch, correct?)
February 19th, 2003, 03:14 PM
Yes, so subtracting the ASCII value of '0' would be the simpler way to go.
Even simpler and more portable (and more C-ish):
int_value = ch - '0';
That way, you won't need to know the ASCII code for '0', plus it should work in any other character-code system, like EBCDIC.
Now, if you have multiple digits that you want to convert to their numeric value -- eg, "42" -- , then atoi() would be the way to go. Just copy the characters into a char array, add a null ('\0') and pass the array name to atoi(). Otherwise, you could construct the integer value yourself, multiplying the previous value by ten and then adding the new digit.
February 19th, 2003, 04:09 PM
That is what I was looking for.