| TIP: Click on subject to list as thread! | ANSI |
| echo: | |
|---|---|
| to: | |
| from: | |
| date: | |
| subject: | Pointer in functions? |
> why doesn't the following work. I know that I can get it to work
> by allocating the memory that str points to before calling printstr(); but
> I want to know why? Is it because the allocated memory in
> printstr(); goes out of scope when you leave the function?
No, the variables in each case are different. If you assign the memory
prior passing it to the function, the _value_ contained in the original
pointer is passed. If you later change it or assign to that variable, that
change won't be reflected in the variable declared in main().
This is a modified version that passes a pointer to the original pointer
(not the value of the pointer).
#include
#include
#include
#define _MAX_SIZE_ 255
printstr(char *argv[], char **s );
/* ^ */
main( int argc, char *argv[] )
{
char *str;
printstr( argv, &str );
/* ^ */
printf("The name of this file is : %s\n", str );
free(str);
}
printstr(char *argv[], char **s )
/* ^ */
{
*s = malloc( sizeof(char) * _MAX_SIZE_ );
/* ^ */
strcpy(*s,argv[0]);
/* ^ */
printf("In (printstr), The name of this file is : %s\n", *s);
/* ^ */
}
This should work in the way you want.
cheers,
david
---
* Origin: Unique Computing Pty Ltd (3:632/348)SEEN-BY: 50/99 54/54 620/243 623/625 632/103 301 348 386 998 633/371 634/384 SEEN-BY: 635/210 502 503 544 636/100 670/206 711/409 430 807 808 809 932 934 SEEN-BY: 712/623 713/888 714/906 800/1 @PATH: 632/348 635/503 50/99 54/54 711/808 809 934 |
|
| SOURCE: echomail via fidonet.ozzmosis.com | |
Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.