Garbage characters in a string

I wrote some code to create the correct character pyramid.

However, when I execute the program, the last two lines of the pyramid contain garbage characters placed after them, even when they exceed 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 do garbage symbols come from? This is only on the lines after the third.

+3


source to share


3 answers


The problem in your code is that you didn't terminate your string with \0

(null). 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 not an expert, but I've read the following in many typical books: int

Arrays in C are initialized to 0

, and arrays are char

garbage-initialized.

And yes, forgot to mention, this is not dolla

, it array

.

+3


source


char array[ROW+1] = {0};

will help you a lot. You may have assumed that the array is empty, but it was filled with random characters. By initializing with, the {0}

array starts with all zeros.



I am guessing that this dolla

is a transcription error and that either dolla

should be array

or is array

used to refer to dolla

.

+2


source


You will probably overstep the values ​​in the array to make a pyramid that prints out the garbage values ​​that were there before you even compiled your code. When you are printing values, rather than printing the entire array (which means that garbage values ​​can be included in it), you can print to the point where you have valid values, and this can be done by entering the null character "\ 0" to the end of the array. Also array initialization would be the best choice here as then you can debug your code better after seeing the output.

0


source







All Articles