Garbage characters in string

2.2k views Asked by At

I've written code to make a right pyramid out a character.

However, when I execute the program, the last two lines of the pyramid have garbage characters placed after them even when it exceeds the size of the array.

The code is here:

#include <stdio.h>
#include <string.h>

#define ROW 5
int main(void) {
  char array[ROW];
  int x = 0;
  int row = 0;

  for (row = 0; row < ROW; row++) {
    array[x] = 'a';
    if (x < ROW) {
      printf("%s\n", dolla);
    }
    x++;
  }
  getchar();
}

Where are the garbage characters coming from? It's only on lines after the third.

3

There are 3 answers

1
Pranav Totla On

The problem in your code is that you have not terminated your string with \0 (null) character. Here's a workout for your code:

#include <stdio.h>
#include <string.h>
#define ROW 5
int main(void)
{
char array[ROW];
int x = 0;
int row = 0;


for(row = 0; row < ROW; row++)
{
array[x] = 'a';

    if(x < ROW)
    {
        array[x+1]='\0';
        printf("%s\n", array);
    }
x++;
}

getchar();
}

I'm no specialist, but I've read the following in many typical C books: int arrays in C are initialized to 0, while char arrays are initialized to garbage.

And yeah, forgot to mention, it's no dolla, it's array.

3
JS1 On

char array[ROW+1] = {0}; will help you a lot. You might have assumed array was empty but it was full of random characters. By initializing with {0}, the array starts with all zeroes.

I'm going to assume dolla was a transcription error and that either dolla should be array or that array used to be named dolla.

0
NoorUllah On

You are probably exceeding the values in the array to make the pyramid which results in printing out garbage values that were there before you even compiled your code. When you print the values, rather than printing out whole array ( which means there can be garbage values included ) you can print up to the point where you have valid values and this can be done by introducing a null character '\0' at the end of the array. Also initializing you array would be a better choice here as then you can debug your code better after seeing the output.