Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

First character of a string pointer.

Status
Not open for further replies.

ushtabalakh

Programmer
Jun 4, 2007
132
I'm trying to have the first character of *p stored in c, or printed directly. I should not use any external libraries I wanna do it using pointer arithmatics and stuff...

Code:
	char *s = "this is a test";

	char *p = s;
	while (*p != '\0'){
		p++;
		char c = *p;
		printf("%s\n",c);
	}
Any clues?
 
If you want to print a single character, the format is %c, not %s.

Also, you'll end up trying to print the \0 at the end.


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
basicaly, you just need to do:

char *s = "this is a test";

char c = *p; /* will store the first character of the string 's' in the character variable 'c'*/
printf("%s\n",c);

 
yeah, also you should not use: printf("%s\n",c); to print
a single character but printf("%c\n",c); instead.
 
do not use the first p++ before you assign it to character 'c'.
move p++ after assigning to *p to c than increment p and print the character using %c.
so program look like this and will print first character of string and then all other one by one
(your program will start printing string from second character not from first character so try to run belove program ,it will print all the character from the string )
Code:
 char *s = "this is a test";

    char *p = s;
    while (*p != '\0'){
       
        char c = *p;
        p++;
        printf("%s\n",c);
    }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top