I decided to do the CS50 course again and tried to go about solving some of the problems differently. There is a task where you have to print pyramids with two spaces between each half using the '#' char with a height determined by the user (should be between 1 and 8 though). If the height was 4 it should look like this for example:
# #
## ##
### ###
#### ####
This works fine when the integer is anything between 1 and 7 but when it is 8 it starts adding gibberish non-ascii characters to the right of the left half of the pyramid.
This is my code:
int main(void)
{
int h = 0;
while (h < 1 || h > 8) {
printf("Height: ");
scanf("%d", &h);
}
for (int i = 0; i < h; i++) {
char a[h + 1];
char b[h - (h - i) + 2];
for (int j = 0; j < h; j++) {
a[j] = h - j > i + 1 ? ' ': '#';
if (i <= j) b[i] = '#';
}
printf("%s %s\n", a, b);
}
}
I thought it might be a memory thing so I just set the size of the char arrays to 3000. It stopped printing gibberish and still worked fine for heights 1 - 7 but when the user put anything more than 7 the pyramid looked skewed like this:
#
# ##
## ###
### ####
#### #####
##### ######
###### #######
####### ########
Why is this happening and how can I fix it?
Thank you to everyone who responded! The problem was that I didn't set null terminators in the string. This is the working function:
int main(void)
{
int h = 0;
while (h < 1 || h > 8) {
printf("Height: ");
scanf("%d", &h);
}
for (int i = 0; i < h; i++) {
char a[h + 1];
char b[h - (h - i) + 2];
for (int j = 0; j < h; j++) {
a[j] = h - j > i + 1 ? ' ': '#';
if (i <= j) b[i] = '#';
}
a[h] = '\0';
b[h - (h - i) + 1] = '\0';
printf("%s %s\n", a, b);
}
}
It looks like there are few issues with your code.
#include <stdio.h>
int main(void) {
int h = 0;
while (h < 1 || h > 8) {
printf("Height: ");
scanf("%d", &h);
}
for (int i = 0; i < h; i++) {
char row[2 * h + 3]; // Maximum required size for the row
for (int j = 0; j < 2 * h + 2; j++) {
if (j < h - i || (j >= h && j < h + 2) || j > h + i + 1) {
row[j] = ' ';
} else {
row[j] = '#';
}
}
row[2 * h + 2] = '\0'; // Null-terminate the string
printf("%s\n", row);
}
return 0;
}