0

Why do I get a from the console with the following code?

 char array1[] = "Hello World";

 char ch = array1;
 printf(" %s" , ch);

(We are instructed not to do this with a pointer)

1
  • How is it that you've been instructed not to do this with a pointer, but the error was that you were missing a * from pointer notation? Commented Sep 24, 2009 at 3:13

1 Answer 1

6

Because you need to make ch a pointer to a character. The compiler should have given you a warning that you were assigning a character pointer to a character variable, and it should have warned you that you were trying to printf("%s") on a non-character-pointer variable -- if it didn't, you should turn up your compiler's warning level!

Just adding that one little, easily-forgotten star makes it work correctly:

#include <stdio.h>
int main()
{
    char array1[] = "Hello World\n";

    char *ch = array1; printf(" %s" , ch);
    return 0;
}

I also took the liberty of adding a newline on the end of your string and putting it in a proper main function, for the sake of completeness.


I just noticed that you said you "aren't allowed to do this with pointers" -- pretty much the only other way to do it is to print out character-by-character until you hit a null terminator:

#include <stdio.h>
int main()
{
    char array1[] = "Hello World\n";

    int i;
    for (i = 0 ; array1[i] != '\0' ; i++)
    {
        printf("%c", array1[i]);
    }
    return 0;
}

output:

$ ./a.out
Hello World

A more robust approach would be to also put a limit on how many characters you will print out, but just checking for \0 is probably fine enough for what seems to be a homework assignment.

Sign up to request clarification or add additional context in comments.

3 Comments

Mark, I've entered the above code, but Im trying to check the 4th element in this string with printf("%s", s[3]); but the project freezes on me =(
@metashockwave s[3] is a character refrence so you need to change the %s to %c to print just that character.
why not printf( "%s", array1 );?

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.