ir*******@gmail.com said:
In Chapter 2 of the book 'C Unleashed' the author states that this
code
#include <stdio.h
void increment(char *p)
{
++p
}
int main(void)
{
char *s = "Hello world";
increment(s);
printf("%s\n", s);
return 0;
}
"doesn't work (and in fact results in undefined behavior):"
I state no such thing. What I actually say is:
(begin quote)
What is actually happening here is that the addresses [...] are being
passed - by value. We can see this most clearly with a simple
demonstration program:
#include <stdio.h>
void increment(char *p)
{
++p;
}
int main(void)
{
char *s = "Hello world";
increment(s);
printf("%s\n", s);
return 0;
}
If C passed pointers by reference, this program would print
ello world
But it doesn't. It prints
Hello world
This indicates that the modification of p by the increment() function
has no effect on the original pointer s. This is exactly the behavior
we would expect of pass-by-value. For precisely the same reason, this
code doesn't work (and in fact results in undefined behavior):
#include <stdio.h>
int openfile(char *s, FILE *fp)
{
fp = fopen(s, "r");
return fp ? 1 : 0;
}
int main(void)
{
FILE *fp;
char buffer[1024];
if(openfile("readme", fp))
{
while(fgets(buffer, sizeof buffer, fp))
printf("%s", buffer);
fclose(fp);
printf("\n");
}
return 0;
}
(end quote)
The original text, btw, spelled "behavior" as "behaviour", but it got
mangled during production (apparently on purpose).
>
Modified code that does work, that is, code that prints "ello world"
is not shown.
What is is proper way to modify the code so that "ello world" is
printed?
This has already been answered elsethread.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.