Reputation: 655
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[]="shevchenko ac milan";
printf("%s",&a);
}
This is prints "shevchenko ac milan"
but
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[]="shevchenko ac milan";
printf("%s",&a+1);
}
Why does this print junk characters?
Upvotes: 2
Views: 3412
Reputation: 6695
This is happening because when you say &a + 1 .This would make the pointer reach one location ahead of the end of string.This is the pointers basic operation.You could check this for an integer array also.
For e.g.
int a[]={1,2,3,4,5};
printf("%d",&a+1);
would always print garbage value.
That is it would now going to point to next 1D array which is actually not there.Thus garbage value gets printed.
Upvotes: 1
Reputation: 263469
When you increment the "address that points to an address", you get an unassigned value. fbrereto is right, you only need to pass a for the pointer to the first position, and a+1 to point to the second position in the array.
Upvotes: 0
Reputation: 26060
&a
is of type pointer to a char[20]
.
When you do &a+1
you'll go to the next char[20]
item in memory, thus you'll go after a
.
You should instead have a char*
: by summing 1 to it you'll go to the next char
.
To obtain a char*
you can just use a
(it decays in a char*
by doing this), and thus a+1
to go the next char.
Upvotes: 10
Reputation: 35925
You don't need to pass the address of a (&a
) - in C a string is an array of char
s, so a
is already an address. Try:
char a[]="shevchenko ac milan"; printf("%s", a);
and
char a[]="shevchenko ac milan"; printf("%s", a+1);
Upvotes: 3