I am thinking of something like:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main(void) {
//test pointer to string
char s[50];
char *ptr=s;
printf("\nEnter string (s): ");
fgets(s, 50, stdin);
printf("S: %s\nPTR: %s\n", s, *ptr);
system("PAUSE");
return 0;
}
Or should I use a for loop with *(s+i) and the format specifier %c?
Is that the only possible way to print a string through a pointer and a simple printf?
Update: The printf operates with the adress of the first element of the array so when I use *ptr I actually operate with the first element and not it’s adress. Thanks.
The
"%s"format specifier forprintfalways expects achar*argument.Given:
it looks like you’re passing an array for the first
%sand a pointer for the second, but in fact you’re (correctly) passing pointers for both.In C, any expression of array type is implicitly converted to a pointer to the array’s first element unless it’s in one of the following three contexts:
(I think C++ has one or two other exceptions.)
The implementation of
printf()sees the"%s", assumes that the corresponding argument is a pointer to char, and uses that pointer to traverse the string and print it.Section 6 of the comp.lang.c FAQ has an excellent discussion of this.