When i use j>=num-i in the inner loop ,program will throw a segmentation fault.
#include <iostream>
using namespace std;
int main(){
cout << "Enter the number of rows: ";
int num;
cin >> num;
for (size_t i = 1; i <= num; i++)
{
char ch[num];
for (size_t r = 0; r < num; r++)
{
ch[r]='.';
}
for (int j = num-1 ; j >=num-i; j--)
// when i = num , this part will throw a segmetation fault.
{
ch[j]='*';
}
ch[num] = '\0';
cout << ch <<endl;
}
return 0;
}
But when i use j >= 0 ,and add an if sentence the program will work,why is that?
#include <iostream>
using namespace std;
int main(){
cout << "Enter the number of rows: ";
int num;
cin >> num;
for (size_t i = 1; i <= num; i++)
{
char ch[num];
for (size_t r = 0; r < num; r++)
{
ch[r]='.';
}
for (int j = num-1 ; j >=0; j--)
{
if (j>=num-i)
{
ch[j]='*';
}
}
ch[num] = '\0';
cout << ch <<endl;
}
return 0;
}
why i cannot use j>=num-i as the judge condition in the for loop? Is something i have missed?