0

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?

1

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

11 Comments

Did OP need the +1?
I don't know. Probably not but I kept his logic in place and only checked his problem: that he was printing '?' with %c.
I am confused on the printf statement, where we see arrayPointer+1, doesn't this miss character on first index and point out of bound? I haven't tested it though.
@LuzanBaral forget about +1. it is an error. You will try to print the 0x00 as well and you will miss the first char
@P__J__ Is printf("%c", '\0') legit though?
|
0
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)

1 Comment

Thanks, Another substitute for the problem.
0

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

1 Comment

Thanks, this a complete solution as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.