Aziz Ahmed
Aziz Ahmed

Reputation: 81

Why printing Array of String in c not providing same output?

When the last character matched to the first character of next element of array the output given the last character repeated. What is the reason and what should be the solution ?

Left side is program right side is output

#include <stdio.h>

int main(void) {
  int i ;

  char fact_char[13][2] = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};

  for(i = 0; i < 13; i++){
    printf("%s\n", fact_char[i]);
  }

  return 0;
}

OUTPUT


I
IVV
V
IXX
X
XLL
L
XCC
C
CDD
D
CMM
M

Upvotes: 2

Views: 611

Answers (3)

chux
chux

Reputation: 153348

printf("%s\n", fact_char[i]); expects fact_char[i] to be a string.

A string is a contiguous sequence of characters terminated by and including the first null character. C18

fact_char[11] is not a string as it lacks a null character. It is only 'C', 'M'.

Either allow more space with fact_char[13][3] or print with a width limit. The following will stop printing after 2 characters or until a null character is encountered. fact_char[11] will still not be a string as it lacks a null character.

printf("%.2s\n", fact_c[i]); // limit print width

Upvotes: 1

Barmar
Barmar

Reputation: 780798

Your array declarations don't allow room for the null terminators of the 2-letter strings. Change it to

char fact_char[13][3]

Using %s format to print a char array that doesn't have a null terminator results in undefined behavior.

Upvotes: 5

yhyrcanus
yhyrcanus

Reputation: 3813

Strings in c are null terminated. To represent "IV", you're actually storing 'I','V' and '\0' in memory. When you're printing a two character string, printf is going to keep writing until it finds the next null terminator in memory, which happens to be in the next (single character) string.

To fix this, just make it

fact_char[13][3]

Upvotes: 6

Related Questions