C uses a
Call-by-Value programming model.
You reuse variables name
s inside functions
func and
main, and that makes the explanation more confusing. I will edit your first snippet to eliminate the confusion.
- void func(char *t)
-
{
-
t+=1;
-
}
-
void main()
-
{
-
char s[]="neymar messi";
-
func(s);
-
printf("%s",s);
-
}
main passes
s to
func, which has the effect of copying the value of
main's
s into
func's
t.
func then increments
t, but that has no effect on
main's
s, so line 9 prints the original string.
Now let's look at the second snippet...
- void func(char *t)
-
{
-
t[2]='k';
-
}
-
void main()
-
{
-
char s[]="nekmar messi";
-
func(s);
-
printf("%s",s);
-
}
main passes
s to
func, which has the effect of copying the value of
main's
s into
func's
t.
func then writes 'k' into the third character of the string pointed to by
t.
t has the same value as
s, so it points at the same string that
s points at; thus 'k' is written to the third character of the string pointed to by
s, but that character is already 'k', so this write has no effect.
By the way, in the second snippet you are overwriting a string literal. The C Standard says doing so has unpredictable results. I can't remember if this is formally labeled
undefined behavior or
implementation defined behavior, but either way it is ill-advised.
By the way,
main should always return
int.
By the way, in general, a
printf format string should end with newline. That is, line 9 of both snippets should be: