Reputation: 37
How can I store the value pointed by the char pointer into an integer variable? I have the following code:
main ()
{
int i;
char *tmp = "10";
i = (int)tmp;
printf("value of i is %d",i);
}
Is my code most efficient for the given task? I am using Visual Studio 2008.
Upvotes: 1
Views: 281
Reputation: 91983
A string in C is just an array of characters, and tmp
points to the first character in the string. Your code converts this pointer value (a memory address) to an integer and stores it in i
.
What you really want to do is use strtol
in stdlib:
#include <stdlib.h>
main ()
{
int i;
char *tmp = "10";
i = (int) strtol(tmp, 0, 10);
printf("value of i is %d",i);
}
Upvotes: 3
Reputation: 4252
You should probably look into atoi for string to int conversions.
Note that atoi does no error checking so only use it if you know exactly what your input is (like the constant string you have in your example). Otherwise use Emil Vikström's answer.
Upvotes: 1