2

If i have the following :

char id[5]="1";

and I want to use the id as a integer,i have to convert it first or is enough (int)id to use the value from that string ?

Matt
  • 484
  • 5
  • 15
  • This question should help. http://stackoverflow.com/questions/3420629/convert-string-to-integer-sscanf-or-atoi – FreeNickname Apr 11 '13 at 17:54
  • 1
    Especially note that `(int)id` will compile and is valid C, but does not do what you think it would. It will return the (first) memory address of the string, i.e. the value of the pointer itself. – Kninnug Apr 11 '13 at 17:57

3 Answers3

4

No... you would need to convert it using a function call such as int n = atoi( id )

A char array is just that... an array of char... it is not a number in the sense that you're thinking. You need to use a function call to convert it from the string representation of a value to the actual numerical integer value you're looking for.

K Scott Piel
  • 4,320
  • 14
  • 19
1

You can use atoi to convert the string to an integer:

char id[5] = "1";
int n = atoi(id); // n = 1
Paul R
  • 208,748
  • 37
  • 389
  • 560
1

C does not provide type conversions between strings and numerical data.

To convert from a string to an int, you need to use atoi or (better) strtol. strtol is better, because it does not result in undefined behaviour if the input string is not convertable to a number, and it allows you to detect cases like "42xyz" and react correctly.

Bart van Ingen Schenau
  • 15,488
  • 4
  • 32
  • 41