-4

Simple question, below is my code. The number my compiler returns is 4219296. My question is: why? What is my code doing here?

#include <stdio.h>
char array[];

int main()
{

atoi(array);
printf("%d \n", array);


return 0;

}
emmanuel
  • 9,607
  • 10
  • 25
  • 38
daviegravee
  • 171
  • 2
  • 12

3 Answers3

0

Here that is printing the address of the starting position in of your array. If you use a pointer you will get the value of that.

  printf(" %d \n",*array);

Here atoi is doing nothing.

Karthikeyan.R.S
  • 3,991
  • 1
  • 19
  • 31
0

If i'm not wrong, you want to convert a string containg a numberic value into an integer.

In your code, because of char array[]; atoi() will face undefined behaviour. You need to pass some valid address to the API.

Also, instead of using atoi(), use the safer counterpart strtol().

Check the below code.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char ip[ ] = "12345";
    char *err;

    long int retval;

    retval = strtol(ip, &err, 0);
    printf("strng format : %s, int format %ld\n", ip, retval);


    return 0;
}

O/P

[sourav@broadsword temp]$ ./a.out

string format : 12345, int format 12345

Also, if you change the ip to someting like char ip[ ] = "12A45";, then the o/p will look like

[sourav@broadsword temp]$ ./a.out string format : 12A45, int format 12

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

The function atoi returns the converted value. This value needs to be stored. Here in the above program you are not storing the returned value. So there is no effect on the array variable.

Printing the array in decimal format gives you the address of the array. The program shall print the same value even without the atoi function. To confirm try this:

//...
printf("%d \n", array);
atoi(array);
printf("%d \n", array);

Output remains same.

n0p
  • 3,399
  • 2
  • 29
  • 50