Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm currently programming a version of Conway's Game of Life in C as part of an assignment for my degree course. Within the code, I ask the user to enter an integer representing a menu item describing the game's initial conditions.
When I tested the code surrounding this on it's own, it worked fine, scanning in the values correctly and printing them out fine etc.
However, I have now continued with my code and begun developing the next stage and now suddenly I am getting a segmentation fault which, using printf, I pinpointed back to this very same previously working scanf statement.
Is anyone able to point me in the direction of why this scanf is suddenly giving such a fault, so I can hence address the problem.
My code is as follows:
#include <stdio.h>
#include <math.h>
#include <string.h>
#define WIDTH 60
#define HEIGHT 60
#define NAMELENGTH 128
void initGrid(int choice, int grid[][WIDTH]){
int a,b;
for(a=0;a<HEIGHT;++a){
for(b=0;a<WIDTH;++b){
grid[a][b]=0;
}
}
switch(choice){
case 1 :
grid[6][3]=1;
grid[7][3]=1;
grid[6][4]=1;
grid[7][4]=1;
grid[6][13]=1;
grid[7][13]=1;
grid[8][13]=1;
grid[5][14]=1;
grid[4][15]=1;
grid[4][16]=1;
grid[9][14]=1;
grid[10][15]=1;
grid[10][16]=1;
grid[7][17]=1;
grid[5][18]=1;
grid[9][18]=1;
grid[6][19]=1;
grid[7][19]=1;
grid[8][19]=1;
grid[7][20]=1;
grid[4][23]=1;
grid[5][23]=1;
grid[6][23]=1;
grid[4][24]=1;
grid[5][24]=1;
grid[6][24]=1;
grid[3][25]=1;
grid[7][25]=1;
grid[2][27]=1;
grid[3][27]=1;
grid[7][27]=1;
grid[8][27]=1;
grid[4][37]=1;
grid[5][37]=1;
grid[4][38]=1;
grid[5][38]=1;
break;
case 2 :
grid[29][29]=1;
grid[28][29]=1;
grid[30][29]=1;
grid[29][28]=1;
grid[28][30]=1;
break;
default :
break;
}
}
int main() {
int currGrid[HEIGHT][WIDTH];
//int nextGrid[HEIGHT][WIDTH];
char name[NAMELENGTH];
printf("Welcome to Conway's Game of Life. To Begin, What Is Your Name?\n");
scanf("%[^\n]%*c", name);
int menSelect;
printf("Hello %s, Please Enter the Integer Next to the Item Below That Describes How You Would Like Your Game of Life to Initially Be Set Up\n \n 1. Gosper's Glider Gun \n 2. R-Pentomino\n ", name);
for(;;){
int checkIn=scanf("%d",&menSelect);
if(checkIn!=1){
fprintf(stderr,"Scanf Has Failed to Read In Any Values\n");
}
if(menSelect!=1 && menSelect!=2){
fprintf(stderr,"%s, %d Is Not a Valid Selection\nPlease Try Again\n",name,menSelect);
}else{
break;
}
}
initGrid(menSelect,currGrid);
return 1;
}
The offending line is int checkIn=scanf("%d",&menSelect); from what I can tell but I can't figure out why.
Many thanks
Undefined behaviour because of how you zero the grid. Looks like a copy/paste error.
for(b=0;a<WIDTH;++b){
^^^
You meant b < WIDTH.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
#include <wiringPi.h>
#include <stdio.h>
#define ledPin 0
main()
{
wiringPiSetup()
int x;
for(x=0; x<4; x+1)
{
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
}
}
the error is on line 7 and i've been stuck on it for 2 days (i code in geany)
It sounds like you're getting a compile error on line 8:
wiringPiSetup() /* <-- You need to end the line with ";" */
Your loop should look like this:
for(x=0; x<4; x++) {...} /* "x+1" doesn't change the value of "x", so the loop will never terminate */
The problem is in your for loop.
for(x=0; x<4; x+1)
The third parameter in brackets does not do anything. You probably wanted to increment x and you will do that with x++ or x+=1.
x+1 will return the value, but that will not be stored anywhere.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
/*
Hello World example made by Aurelio Mannara for libctru
This code was modified for the last time on: 12/12/2014 21:00 UTC+1
*/
#include <3ds.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
gfxInitDefault();
char player[1024] = "\x1b[";
int tesx = 1;
char tesxx = tesx + '0';
char ot[] = ";";
char oty[] = "H0";
int test = 3;
char testt = test + '0';
//Initialize console on top screen. Using NULL as the second argument tells the console library to use the internal console structure as current one
consoleInit(GFX_TOP, NULL);
strcat(player, tesxx);
strcat(player, ot);
strcat(player, testt);
strcat(player, oty);
//Move the cursor to row 15 and column 19 and then prints "Hello World!"
//To move the cursor you have to print "\x1b[r;cH", where r and c are respectively
//the row and column where you want your cursor to move
//The top screen has 30 rows and 50 columns
//The bottom screen has 30 rows and 40 columns
printf(player);
// Main loop
while (aptMainLoop())
{
//Scan all the inputs. This should be done once for each frame
hidScanInput();
//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
u32 kDown = hidKeysDown();
if (kDown & KEY_START) break; // break in order to return to hbmenu
// Flush and swap framebuffers
gfxFlushBuffers();
gfxSwapBuffers();
//Wait for VBlank
gspWaitForVBlank();
}
gfxExit();
return 0;
}
why am I getting this error. I am working in C and I'm making a game for the 3ds and I want to be able to control the placement of my player char by using my int variables tesx and test. I don't understand why my offset is 0 and why its going off bounds.
C:/Users/Jeremy/Desktop/gaame/source/main.c:24:9: warning: 'strcat' offset 0 is out of the bounds [0, 0] [-Warray-bounds]
24 | strcat(player, testt);
| ^~~~~~~~~~~~~~~~~~~~~
C:/Users/Jeremy/Desktop/gaame/source/main.c:22:9: warning: '__builtin_stpcpy' offset 0 is out of the bounds [0, 0] [-Warray-bounds]
22 | strcat(player, tesxx);
| ^~~~~~~~~~~~~~~~~~~~~```
The header <string> and the class std::string defined in that header are part of the C++ standard library. The .c suffix of the file main.c implies that it is written in the C language. It appears that you are attempting to use C++ features in the C language. This doesn't work because they are separate languages. You cannot use C++ features in C.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I had tried all the C compiler but keep getting wrong answer on test 1, even though i already try to use the input on test 1 and had received the correct output when I tried it on the DEV c++.
input:
5
0 1 0 1 1
output:
4
this is a case study, so basically 5 in the input means the amount of period.
0 means break time and 1 means study time. if input is 1 total hour of study hours would be added by one, if its 0 there will be no study hence study hours would not be added. there is also a special case, like shown in the input if previously she was studying and now she is having breaks but after the breaks she will have a class (1 0 1) the break will be counted as study time and so study hours will be ++.
any idea? is it the code perhaps?
(the accepted code)
#include <stdio.h>
#include <string.h>
int main()
{
int n,hours=0;
scanf("%d",&n);
char str[n*2];
int x[n];
while ((getchar()) != '\n');
fgets(str, n*2 , stdin);
char* piece = strtok(str, " ");
for(int i=1; piece != NULL ; i++)
{
sscanf(piece, "%d" , &x[i]);
piece = strtok(NULL, " ");
}
for(int i=0 ; i<n+1; i++)
{
if(i==0)
{
if(x[0]==1){
hours++;
}
}
else
{
if(x[i]==0)
{
if( x[i-1]==1 && x[i+1]==1 )
{
hours++;
}
}
else
{
hours++;
}
}
}
printf("%d\n",hours);
return 0;
}
You are using [ i-1 ] and when index is 0 in for some inputs you will get a garbage value. May be it will work for some inputs,and not for others.
The most common reason the online judge do not accept the solution even though the answer is correct in other ide is either because you have extra indentation in your program or a loop doesn't terminate, or you get garbage value or you try incrementing a not defined value.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am trying to create a program that will switch between "modes". For example here are little snippet of the code:
int main()
{
int mode,input;
mode = 1;
for(;;)
{
scanf("%d", &input);
switch(input)
case 1:
if(mode = 1)
{
//statements go here;
mode = 2;
}
else
{
//statements go here;
mode = 1;
}
break;
}
}
So what I'm trying to do is get the program to switch between mode 1 and mode 2 by the input of the 1 button. However each time I press the number 1 key, it will only print the statements of mode 1 but won't switch to mode 2 and print out the statements for mode 2 if i press the number 1 button a second time. Is there something fundamentally wrong with my code?
*restriction: I must use the switch statements in the program.
To test the value of a variable you need double equals:
if(mode == 1)
I want to code a simple bean machine program. The program will accept user input for the number of balls and the number of slots, and will calculate the path of each ball. The number of balls in each slot will be printed as a histogram as well.
I tried my best to keep the code short and sweet, yet the best I have managed is 112 lines long. When I ran my code, I received no errors. However, the output seems to have run into some sort of an infinity loop (The '#' symbol which was used to represent numbers in the histogram keeps on printing forever for some reason unknown to me).
Apparently, there is something wrong with my logic somewhere... or a silly little mistake in syntax(but it would have shown up as error, wouldn't it?)... In a nutshell, I cannot figure out exactly what is the problem. (I attempted to walk through the whole code process from start to finish, but my mind kept getting tangled up somewhere in the middle of the code, nowhere near the end of the code either).
Where exactly does my logic go wrong?(Or have I taken the wrong approach to the whole problem?) I do not wish to know the correct code, so that I am able to learn during the whole process of re-editing my code.
Any help (hopefully no model-code answers though), even as a single comment, is tremendously appreciated! :)
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
#include <stdbool.h>
#include <time.h>
//Pls excuse my extensive use of libraries even though I don't really use them
int intchecker(float x)
{
if (floor(x)==x && ceilf(x)==x)
{
return 0;
}
else {
return 1;
}
}
int main(){
char line[] = " +----+----+----+----+----+----+----+----+----+----+---+";
char numbers[] = " 0 5 10 15 20 25 30 35 40 45 50";
float balls,slots;
int slotarry[9],tlevel,ballnum,column,lcounter=0,slotsduplicate=1,y;//tlevel-number of levels in the triangle
srand(time(NULL));
int r;
printf("==========================================================\nGalton Box Simulation Machine\n==========================================================\n");
printf("Enter the number of balls [5-100]: ");
scanf("%f",&balls);
while (balls>100 || balls<5) {
printf("\nInput is not within the range. Please try again.");
printf("\nEnter the number of balls [5-100]: ");
scanf("%f",&balls);
}
while (intchecker(balls)==1) {
printf("\nInput is not an integer. Please try again.");
printf("\nEnter the number of balls [5-100]: ");
scanf("%f",&balls);
}
printf("Enter the number of slots [2-10] : ");
scanf("%f",&slots);
while (slots>10 || slots<2) {
printf("\nInput is not within the range. Please try again.");
printf("\nEnter the number of slots [2-10] : ");
scanf("%f",&slots);
}
while (intchecker(slots)==1) {
printf("\nHow can there be a fraction of a slot? Please re-enter slot number.");
printf("\nEnter the number of slots [2-10] : ");
scanf("%f",&slots);
}
tlevel=slots-1;
for(ballnum=1,column=0;balls>0;balls--,ballnum++,column++){
if (column%5==0){
printf("\n");
}
if (ballnum<10){
printf("[0%d]",ballnum);
}
else{
printf("[%d]",ballnum);
}
for(;tlevel>0;tlevel--){
r = rand() % 2;
if (r==0){
printf("R");
}
else {
printf("L");
lcounter++;
}
}
slotarry[lcounter]++;
tlevel=slots-1;
lcounter=0;
printf(" ");
}
printf("\n\n%s",numbers);
printf("%s",line);
char line2[] = "\n +----+----+----+----+----+----+----+----+----+----+---+";
for(;slotsduplicate<=slots;slotsduplicate++){
if (slotsduplicate<10){
printf("0%d|",slotsduplicate);
}
else{
printf("%d|",slotsduplicate);
}
y=slotarry[slotsduplicate];
if (y==0){
printf(" 0");
}
else{
for (;y>0;y--){
printf("#");
}
printf(" %d",slotarry[slotsduplicate]);
}
printf("%s",line2);
}
return 0;
}
Note:This is not completely error-free. This is just my first draft. I just wish to find out why there is an infinite loop.
Here's how I found the problem. First of all, I think it is a bit of a code smell to have a for loop without anything in the initial assignment section. Couple that with the fact that it seems to print # forever, and it looks like y has a garbage value at the beginning of the loop to print the #s.
So I ran your code in the debugger and paused it when it started printing loads of hashes. I checked the value of y and sure enough it was some unfeasibly high number.
Then I checked where y comes from and found you get it from slotarray. I printed it in the debugger and found that all the values in it were unfeasibly high or massively negative numbers. Obviously, slotarray wasn't being initialised correctly, so I looked for where it was initialised and bingo!
Stack variables (of which slotarray is one) must be explicitly initialised in C. I fixed your code with a call to memset.
The whole debugging process I have just outlined took something less than a minute.
ETA As #EOF points out, there is another bug in that slotarray is defined to contain nine slots (indexed 0 - 8) but you allow people to enter 10 slots. This is a buffer overflow bug.