开发者

C String prints junk characters

开发者 https://www.devze.com 2023-02-12 00:59 出处:网络
#include <stdio.h> #include <stdlib.h> int main开发者_Go百科() { char a[]=\"shevchenko ac milan\";
#include <stdio.h>
#include <stdlib.h>
int main开发者_Go百科()
{
    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?


&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.


You don't need to pass the address of a (&a) - in C a string is an array of chars, 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); 


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消