0

When I try to print an array of characters as a string with a variable before, like that

int main()
{
    string text = "a";
    char str[2] = {'a', 'b'};
    printf("%s\n", str);
}

I get this output ab @ and I don't have ANY idea where this @ came from. It's bugging my "substitution.c" from pset2

1 Answer 1

1

From man printf

s

If no l modifier is present: The const char * argument is expected to be a pointer to an array of character type (pointer to a string). Characters from the array are written up to (but not including) a terminating null byte ('\0');....

A char array cannot be treated as a string (char *) unless it has a terminating null byte (\0). (I don't recall if this topic has been discussed at this point in the courseware). The @ comes from the memory after str and before a null byte is encountered.

One option in substitution is to print each char (with %c directive) as it is ciphered.

2
  • I just thought it was strange, because if i remove the variable string text = "a"; it prints without the @.
    – ebonatto
    Commented Jan 23, 2022 at 23:39
  • If you remove that line, the char array is assigned a different memory location. It's an unpredictable result. Commented Jan 24, 2022 at 9:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .