Reputation: 39
I wrote the following code:
char arrayD[] = "asdf";
char *arraypointer = &arrayD;
while(*arraypointer != '\0'){
printf("%s \n", arraypointer+1);
arraypointer++;
}
I tried %d %c to print each character. However, with %c I get "? ? ? ?", with %s I get "sdf sd f ". etc. What am I missing here?
Upvotes: 0
Views: 144
Reputation: 47
hey you were not dereferncing the pointer. you did
arrayptr
but you need to do *arrayptr
. Also you need to use %c if you are printing single character.
here is the code
#include <stdio.h>
int main()
{
char arrayD[] = "asdf";
char *arraypointer = arrayD;
while(*arraypointer != '\0'){
printf("%c \n", *(arraypointer));
arraypointer++;
}
return 0;
}
output :
a
s
d
f
Upvotes: 0
Reputation: 68013
void print_string_by_chars(const char *str)
{
while(*str)
{
putc(*str++, stdout);
putc('\n', stdout);
}
}
usage in your case:
print_string_by_chars(arrayD)
Upvotes: 0
Reputation: 709
You're printing pointer addresses, instead of what the pointer is pointing to. Also arrayD is the address, you don't need &arrayD. Here is a complete working sample:
#include <stdio.h>
int main()
{
char arrayD[] = "asdf";
char *arraypointer = arrayD;
while(*arraypointer != '\0'){
printf("%c \n", *(arraypointer+1));
arraypointer++;
}
return 0;
}
Upvotes: 2