Re: return a string
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Fri, 29 Apr 2005 23:50:47 GMT
muzgocrust@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (iru_muzgo) writes:
> Nascimento,
> you cannot assign a char to a string like that:
> tralha = "#"
> you can do it like this: tralha[0]='#';
> A more elegant code for your purpose goes like this:
>
> --- tralha.c ---
>
> void
> ptr_tralha(char *s)
> {
> while (*s != '\0') /* while the contents of s are different
> * from NULL */
No. NULL is (a macro that expands to) a null *pointer* constant.
'\0' is a null character, sometimes referred to as NUL. Using the
term NULL to refer to a character value is misleading.
> *s++ = '#'; /* s = '#' . increment s */
> }
>
>
> int
> main(void)
> {
> char s[5];
> ptr_tralha(s);
> puts(s);
>
> return 0;
> }
Your array s is not initialized before you pass its address to
ptr_tralha(). Inside ptr_tralha(), you loop over the array until you
find a '\0' character, but there's no reason to assume that you ever
will. Unless there happens to be a '\0' character somewhere within s,
the loop in ptr_tralha() will go past the end of the array, invoking
undefined behavior.
I just tried compiling and running your program, and it printed a
string of 5 '#' characters followed by a newline. Apparently there
just happened to be no '\0' characters in s itself, but there just
happened to be a '\0' character immediately following it in memory.
This is just one of the infinitely many possible consequences of
undefined behavior.
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.
- References:
- re:return a string
- From: iru_muzgo
- re:return a string
- Prev by Date: Re: [OT]How to get file size?
- Next by Date: Re: return a string
- Previous by thread: re:return a string
- Next by thread: re:return a string
- Index(es):
Relevant Pages
|