Difference between *str and atoi(str)
I was tokenizing, and used strtok on a text file (which has been read into an array 'sto开发者_如何学JAVAre') with the delimiter '='
so there was a statement in the file : TCP.port = 180
And I did:
str = strtok(store, "=");
str= strtok(NULL, "=");
Now if I do *str
, it gives me '82' (probably some junk value)
but atoi(str);
gives me 180 (the correct value)
I was hoping someone could shed light onto this, shouldn't dereferencing str give me 180 too?
Compile and run this program. It should give you a better idea of what's going on.
#include <stdlib.h>
#include <stdio.h>
int main(void) {
const char *s = "180";
printf("s = \"%s\"\n", s);
printf("atoi(s) = %d\n", atoi(s));
printf("*s = %d = '%c'\n", *s, *s);
return 0;
}
Here's the output:
s = "180"
atoi(s) = 180
*s = 49 = '1'
No. atoi
gives you the integer represented by the string str
points to. Dereferencing str
(*str) gives you the value of the char str
points to (which is not the value you wrote).
You need to understand exactly how strings work in C to see what's going on here. The str
variable is a pointer to the first character in the string. Dereferencing str
gives the value pointed to by str
, namely the character '1'
. Similarly, dereferencing str+1
will give you the next character, '8'
. You can see how the end of the string is signified with *(str+3)
(or, equivalently, str[3]
), which gives a null byte. The function atoi
knows how to interpret the characters as a base-10 string of ASCII characters, which is much more complicated than a dereference.
精彩评论