Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   How standard atoi works? (http://www.velocityreviews.com/forums/t440900-how-standard-atoi-works.html)

jigsaw@gmail.com 01-15-2006 04:16 PM

How standard atoi works?
 
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


Walter Roberson 01-15-2006 04:26 PM

Re: How standard atoi works?
 
In article <1137341787.719416.131460@o13g2000cwo.googlegroups .com>,
<jigsaw@gmail.com> wrote:
>int main()
>{
> int i = 0;
> char w[20];


> i = atoi(getnumber1());


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


> p = w;


> 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.
--
Prototypes are supertypes of their clones. -- maplesoft

jigsaw 01-16-2006 02:40 AM

Re: How standard atoi works?
 
Got it. Thank you Roberson.

Thanx and
Regards,

jigsaw



All times are GMT. The time now is 07:41 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.