Re: local/pointers ? HELP

From: Artie Gold (artiegold_at_austin.rr.com)
Date: 05/31/04


Date: Mon, 31 May 2004 15:15:38 -0500

flavius wrote:
> why won't be changed the value stored at *s changed, but only local ?
> how would it look like to modify it's value in main too ?

In C all arguments are passed by *value*; whatever you do to an argument
within a function is gone once the function has exited. If you want teh
value of an argument be mutated by a function you need to pass a pointer
to it.

Unfortunately, that is not the only thing you do not yet understand.
Fortunately, given the word `learn' in the name of this newsgroup,
you've come to the right place.

Hopefully the comments below will help.
>
> void ch_c(char *c)
> {
> c="world";

Here, you have reassigned `c', a parameter local to the function ch_c();
it now points to a chunk of memory containing the characters: 'w', 'o',
'r', 'l', 'd', '\0'. As `c' is local to ch_c() this change will not be
visable once the function exits...

> printf("inside: %s\n",c);

...but is visable in the above call to printf().
> }
>
> int main(void)
> {
> char *s;
> s=malloc(6);
> if(!s)
> return 1;

The variable `s' now points to a freshly allocated chunk of memory
capable of holding 6 chars.

> s="hello";

Oops. You've now reassigned `s' to point to an anonymous array of const
char containing 'h', 'e', 'l', 'l', 'o', '\0'. Since you no longer have
a pointer to the memory you allocated with malloc() above, you've
introduced a memory leak.

> printf("%s\n",s);

This line prints `hello', as that's what `s' is now pointing to.

> ch_c(s);

The variable `s' points to exactly what it did before the call to ch_s().

> printf("%s",s);
> getch();

This is a non-standard function. It would be a good idea *not* to use
non-standard functions in posts to a.c.l.l.c-c++.

> return 0;
> }
>
> //demonstrative purpose only

OK. Let's rewrite this so it behaves the way you want.

#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* for strcpy() */
/* when posting here always show what preprocessor directives you've
    actually used */

void ch_s(char *s) {
    strcpy(s, "world");
    printf("inside: %s\n", s);
}

int main(void) {
    char *s;
    s=malloc(6);
    if(!s)
      return EXIT_FAILURE; /* 0, EXIT_SUCCESS and EXIT_FAILURE
                              are the only standard exit codes */

    strcpy(s, "hello");
    printf("%s\n",s);
    ch_c(s);
    printf("%s",s);
    getc();
    return 0;
}

Make note of the differences between the code you provided and the code
in my response; hopefully it will be enough to get you started. If not,
by all means post any further questions you might have.

HTH,
--ag

-- 
Artie Gold -- Austin, Texas