Telmo Ferreira Telmo Ferreira - 23 days ago 5
C Question

C Array char - When I try to write position 0, the program writes the position 0 and 1

I'm writing a program and I need to store one character on a

char
array.

My problem is when I try to write the char array, the
postion[0]
prints the
postion[0]
+
position[1]
+
position[2]
, and I only want to get the character at
position[0]
.

Here is a program that I wrote just to solve this problem:

#include <stdlib.h>
#include <stdio.h>

int main()
{

char position[3] = { '\0', '\0', '\0'};

int Number;

int i;

for (i = 0; i < 3; i++)
{
printf_s("\n\nNumber-> ");
fflush(stdin);
scanf_s("%d", &Number);

position[Number - 1] = 'O';
}

printf("\n\n%s", &position[0]);
printf("\n\n%s", &position[1]);
printf("\n\n%s\n\n\n", &position[2]);


system("pause");
return 0;
}


Program output

What was my mistake?

Answer

The reason is that you are not just printing that char but the whole "string", for example

printf("%s\n", &position[0]);

is exactly the same as

printf("%s\n", position);

Then,

printf("%s\n", &position[1]);

is equivalent to printing the string starting at the second character instead of the first.

But that's not a real problem in your code, a real problem is that when Number == 3 you have no null terminator, leading to undefined behavior in any of the printf()s no matter whether they are intended or a mistake from your lack of understanding how printf() works and what each specifier does, you MUST read documentation carefully before using any function.

To fix the problem, you can simply print the actual character. For that you have to use the %c specifier instead of %s, like this

printf("%c\n", position[1]);

would print the second element of the array.

Other issues with your code that I recommend you to fix are

  1. Check the value of Number before trying to access the array, if it's big enough you could end up having inexplicable behavior, or it might be negative which would also be a problem.

  2. Check the return value of scanf_s() to ensure that you did receive valid input from the user.

  3. Do not use \n at the beginning of a line as it's awkward and most programmers don't do it unless it's really necessary.

  4. Do not use system("pause") as it's simply a non standard way to deal with IDEs that probably expect a GUI program with an event loop instead of a command line program with text output.