How standard atoi works?

J

jigsaw

hi all,

Hereunder two versions of reading a word from stdin stream:

/* code starts */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

char *
getnumber1(void); /* return a word from stdin */

void
getnumber2(char *); /* read a word from stdin and store it in the char*
*/

int main()
{
int i = 0;
char w[20];

i = atoi(getnumber1());
printf("getnumber1 = %d\n", i);
i = 0;
getnumber2(w);
i = atoi(w);
printf("getnumber2 = [%s]\n", w);
printf("getnumber2 = %d\n", i);
return 0;
}

char *
getnumber1(void)
{
char w[20];
char *p;
int c;

p = w;
while (isspace(c = getchar()))
;
if (c != EOF)
*p++ = c;
for (;;) {
if (isspace(c = getchar())) {
ungetc(c, stdin);
break;
}
*p++ = c;
}
*p = '\0';
printf("getnumber1 = [%s]\n", w);
return w;
}

void
getnumber2(char *w)
{
char *p;
int c;

p = w;
while (isspace(c = getchar()))
;
if (c != EOF)
*p++ = c;
for (;;) {
if (isspace(c = getchar())) {
ungetc(c, stdin);
break;
}
*p++ = c;
}
*p = '\0';
return;
}
/* code ends */

I use bc++5.5 as compiler.
the input and output of this small program is like this:

D:\c\scan>getnum
12
getnumber1 = [12]
getnumber1 = 1
12
getnumber2 = [12]
getnumber2 = 12

You can see that results of getnumber1 and getnumber2 are the same.
(12)
but the output of atoi are diffrent.
Can anyone do me a favor to explain the diffrence?

Thanx and
Regards,

jigsaw
 
W

Walter Roberson

int main()
{
int i = 0;
char w[20];
i = atoi(getnumber1());
char *
getnumber1(void)
{
char w[20];
char *p;
int c;
return w;

When you return a char[n], the result is not that the character string
contents are somehow transfered back: the results are that the
address of the char[n] array is transferred back. Unfortunately for
you, char w[20] in this context is a local variable of automatic
duration, so its address is not valid after the return of the routine
it is created in. You are thus attempting to employ undefined
behaviour.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top