1

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.

Jonathan Eustace
  • 2,469
  • 12
  • 31
  • 54
Vicky
  • 37
  • 2
  • 2
  • 7

2 Answers2

3

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);
}
Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
  • Just a note, his code does not convert the first char, but stores the address of the first char array in i. –  Apr 16 '13 at 07:35
  • Thanks for your response, actually here the value of tmp is unknown, because i am reading the value of tmp from another file in that case i cannot use strtol right? – Vicky Apr 16 '13 at 08:49
  • 1
    Of course you can, as long as you are aware that if `tmp` doesn't start with a number then `strtol` will return `0`. – Klas Lindbäck Apr 16 '13 at 09:04
1

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.

Community
  • 1
  • 1
Oren
  • 4,152
  • 3
  • 30
  • 37