Reputation: 1
I am a beginner in pointers. after completing integer arrays and pointers i shifted to character arrays and pointers. i expected the same results but its weird.
int main() {
char chararray[20]="Char Array";
void printarray(char *);
void printarraydirect(char * );
printf("Passing chararray to funtion printarray\n");
printarray(chararray);
printf("Printing directly as c in printarraydirect function");
printarraydirect(chararray);
return 0;
}
void printarray(char *c){
int i=0;
//while(c[i]!= ' ')-----------------------> checks for empty space
while(c[i]!='\0')
{
printf("%c",c[i]);
i++;
}
printf("\n");
}
void printarraydirect(char * c){
printf("Printing c-------------->");
printf("%s\n",c);
int i=0;
printf("Printing c[i]-------------->\n");
// shows error here , if so why didnt it show me error in printarray function. and why didnt it print the whole array when printed c in printarray function..
printf("%s\n" c[i]);
}
Upvotes: 0
Views: 120
Reputation: 291
Basically %s
format specifier expects an address to print to the output stream and it prints until it finds the NULL character(\0
). Here when you give simply c
the base address of the array is passed as the argument. But when you give c[i]
it is the value located at the location (base address + index) i.e, addressOf(c) + valueOf(i).
Upvotes: 0
Reputation: 42159
First of all, you're missing a comma on the line printf("%s\n" c[i]);
. Secondly, c[i]
is a single char
(the element type of your array), hence the %s
formatting is incorrect - it should be %c
to print a single character. Or if you wish to print the entire string from that point onwards, you need to pass the address of that element (&c[i]
), but in this case that is the same as c
since i
is zero.
Upvotes: 2