tags:

views:

80

answers:

1

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....)

+6  A: 

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.

Mark Rushakoff
Thank YOU!!!Thank YOU!!!Thank YOU!!! \n
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.
Robert