My screen isn't printing please help me with this.I'm a beginner and i'm trying to make snake game.
void myScreen()
{
char screen[30][50];
int x = 30, y = 50;
for (int i = 1; i <= x; i )
{
if (i == 1 || i == x)
for (int j = 1; j <= y; j )
screen[i][j] = '#';
else
for (int j = 1; j <= y; j )
if (j == 1 || j == y)
screen[i][j] = '#';
else
screen[i][j] = ' ';
}
for (int i = 1; i <= x; i )
{
for (int j = 1; j <= y; j )
cout << screen[i][j];
cout << endl;
}
}
the screen isn't printing
CodePudding user response:
C arrays are zero-based. That means that the "first" element has actually the index 0. So your code like that:
for(int i=1;i<=x;i )
shall be reworked like that:
for (int i = 0; i < x; i )
Now back to your question: why it isn't printing? The fact is that you are accessing the memory outside of the array, and that is an Undefined Behavior in C . That may be observed as the program that never gets to the code that prints the array.
CodePudding user response:
The reason it becose you don't call the funtion in main()
here how to do it:
int main(){
myScreen();
}
the int main() is when the program is starting.after you can call other functions
They have other reason like you don't import any libraries
#include <iostream>
using namespace std;
add this in the start of your code
CodePudding user response:
You are missing a main function in your code. In C (and C), the main function gets called when you start the program. All other functions that you want to be executed you have to call from this function. Additionally, you start counting your array indexes from 1 - but the first element of an array has 0 as index in most programming languages (including C, C , Python, JavaScript, bash, …, …). This code should work:
#inclue <iostream>
using namespace std;
void myScreen()
{
int x = 30, y = 50;
char screen[x][y];
for (int i = 0; i < x; i )
{
if (i == 0 || i == x - 1)
{
for (int j = 0; j < y; j )
{
screen[i][j] = '#';
}
} else
{
for (int j = 0; j < y; j )
{
if (j == 1 || j == y)
{
screen[i][j] = '#';
} else
{
screen[i][j] = ' ';
}
}
}
}
for (int i = 0; i < x; i )
{
for (int j = 0; j < y; j )
{
cout << screen[i][j];
}
cout << endl;
}
}
int main(int argc, char* argv[]) {
myScreen();
}
