Why does string not exist? [closed] - c

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.

Related

Loop does not stop even after passing condition [closed]

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 1 year ago.
Improve this question
void initTimer (void);
void delay (unsigned long milli);
void main (void)
{
//initialize peripherals
initTimer();
//PORTB all outputs
TRISB = 0;
LATB = 0;
TRISA = 0x0F;
ANSA = 0;
unsigned int allon = 0b1111111111111111;
unsigned int counter;
unsigned int zero = 0b0000000000000000;
if (PORTAbits.RA0 == 1 && PORTAbits.RA1 == 1 && PORTAbits.RA2 == 0)
for (counter = 0; counter < 5; counter++)
{
LATB = allon;
delay(SHORT_DELAY);
LATB = zero;
delay(LONG_DELAY);
}
}
I thought this was like the most foolproof code ever, but it doesnt stop after 5 times, not sure whats going on. The variables are set to binary, which determines which outputs are on or off, zero is alloff, and allon is the opposite
Unlike programs in hosted environments (that is running under OS) which can "return" from main by passing control back to the host, embedded bare-metal programs have nowhere to return. So a typical bare-metal program should have an infinite loop somewhere - either as some even-processing loop, periodic task loop or just in the end of the main function in case it has a finite sequence of actions. In your case it seem to be the last one - you only want to blink few times and halt. So the solution is to place
while(1);
in the end of main function such that it will enter infinite idle loop after execution until reset.

The output is correct but the online judge wouldn't accept? [closed]

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.

Small regex nfa matching while possibly larger matches are running

I'm creating my own lexical analyzer generator, similar to (f)lex. My plan was to make a tool like grep and go from there. Right now I've followed the articles by Russ Cox on creating an analyzer as a virtual machine: https://swtch.com/~rsc/regexp/regexp2.html
The issue I've run into is keeping track of small matches while a larger match is running. An example where this could happen is ".*d|ab" on the input string "abcabcabcabcabcabcd".
Currently, I have an NFA running which is practically the same as the one Cox made. It uses thompsons algorithm to compute dfa sets on the fly from the nfa. The threads are stored in a sparse set. (Preston Briggs and Linda Torczon's 1993 paper, “An Efficient Representation for Sparse Sets,”)
Threads that appear earlier in this list have larger importance and eliminate later threads upon accepting.
My current implementation can find a word matching a regex, but cannot continously keep on matching. To show what currently happens, lets look at the above example regex and string.
The first step makes three threads. Two for the left side of the union, one for the right side. Only the threads taking the wildcard and 'a' advance into the next list.
Step two advances again the wildcard and the thread taking a 'b' this time. It also adds new thread to try and match from this character as starting point.
Step three advances the wildcard and puts the thread running "ab" into an accepting state. Now the newer (less priority) threads are removed and a new threads are added to start matching from this character.
This is where the problem starts: The nfa cannot output a match on "ab" yet. It should wait for ".*d" to finish. This means that for a large input file, a lot of matches should be buffered until the ".*d" terminates (which is at the last character to get the potential largest match)
Thus, the actual question is: What is an efficient way to store these matches or is there another way to not have to potentially buffer the whole input file?
As a side note on the code: The code is so similar to the article of Cox that any questions related to how the code functions can be viewed in the article. Also, I've downloaded and tested the code of Cox and it had the same issue as described above.
What I hope to get with the solution to this question is to get my nfa implementation to match text in the exact same way grep or lex would: with the longest leftmost matches.
As requested, code fragments:
VM opcodes representing ".*d|ab":
0 SPLIT 2, 5
1 ANY
2 SPLIT 1, 3
3 CHAR 'd'
4 JMP 7
5 CHAR 'a'
6 CHAR 'b'
7 ACCEPT
CHAR asserts input character to match first operand.
SPLIT creates two new threads starting at the first and second operand.
ANY matches any input character.
JMP sets the program counter to the first operand.
ACCEPT puts the current thread in an accepting state.
An add function to recursively go through opcodes until reaching an CHAR or ACCEPT opcode then adding these to the next threadlist.
static void recursive_add(struct NFA *nfa, struct Thread *thread)
{
switch(nfa->code[thread->pc])
{
case OPCODE_JMP:
printf(" | jmp\n");
thread->pc = nfa->code[thread->pc + 1];
recursive_add(nfa, thread);
break;
case OPCODE_SPLIT:
{
uint16_t pc = thread->pc;
printf(" | split: %d op1: %d op2: %d\n", thread->pc, nfa->code[thread->pc + 1], nfa->code[thread->pc + 2]);
thread->pc = nfa->code[thread->pc + 1];
recursive_add(nfa, thread);
thread->pc = nfa->code[pc + 2];
recursive_add(nfa, thread);
break;
}
case OPCODE_CHAR: case OPCODE_ACCEPT:
printf(" | char/accept %d\n", thread->pc);
add_sparseset(nfa->nthreads, thread);
return;
default:
fprintf(stderr, "Unexpected opcode %x at program counter %d\n", nfa->code[thread->pc], thread->pc);
exit(1);
}
}
And the main loop, currently a bit messy but this should give a better idea of what the code does.
void execute_nfa(struct NFA *nfa)
{
struct Thread thread;
struct SparseSet *swap;
char c;
for(;;)
{
c = getchar();
printf("Input char %c\n", c);
//add new starting thread for every character
thread.pc = 0;
recursive_add(nfa, &thread);
clear_sparseset(nfa->cthreads);
swap = nfa->cthreads;
nfa->cthreads = nfa->nthreads;
nfa->nthreads = swap;
for(unsigned int i = 0; i < nfa->cthreads->size; i++)
{
thread = *(((struct Thread *)nfa->cthreads->dense) + i);
printf(" thread pc: %d\n", thread.pc);
switch(nfa->code[thread.pc])
{
case OPCODE_CHAR:
if(nfa->code[thread.pc + 1] == c)
{
printf(" Add to next\n");
thread.pc += 2;
recursive_add(nfa, &thread);
}
break;
case OPCODE_ACCEPT:
printf(" accept (still need to do shit)\n");
break;
default:
fprintf(stderr, "Unexpected opcode %x at program counter %d\n", nfa->code[thread.pc], thread.pc);
exit(1);
}
}
}
}

Reading data from text file to linked list, error handling [closed]

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 5 years ago.
Improve this question
I'm currently working on a program that's supposed to read data from a text file, and place said data in a linked list. I've got a pretty good idea of what I'm doing, but the thing is I'm supposed to include error handling that jumps to the next line if there is any errors in the data format in the file.
The file contains information about a number of terminators in the form of their model and their serial number.
An example of the data that can be read is:
TERMINATOR T-800 1
TERMINATOR T-1000 2
TERMINATOR T-800 3
TERMINATOR T-800 4
In the first row above, T-800 is the model, and 1 is the serial number. The four rows above are all valid, but if the fifth row would look something like this:
TORMONUTTUR T-800 1h6
or:
abc 2
, the data should be discarded and the program should continue reading the next row.
I'm currently lost on this, and would appreciate just a nod in the right direction, since I'm not sure how I should even begin with this problem.
One way to not overwhelm yourself is to delegate different actions to different functions so you don't have to worry about everything at once. I would recommend opening the file and reading one line at a time. For each line, you can validate the format, then append the data to your linked list, otherwise do nothing and continue to the next line. That might look something like this.
char line[128];
while(fgets(line, 128, (FILE*)fh) != NULL) {
if(isValidLine(line)) {
// add data to linked list
}
}
The logic is easy to understand there. You just have to define your function isValidLine to read the line to make sure it has valid data in it, and return the corresponding boolean value. To validate this, you might use sscanf or some other string tokenizer to parse the line, or do it yourself manually. For instance, check that it starts with the string "TERMINATOR " and proceed from there. One everything checks out, return true, but at any time the string fails your format requirements, return false right away.
You could read try to read every part of the line as a string (because if serial number was an int for example, 1h6 would be truncated, and you would fail to check if it's valid). For the serial number string, you should check if it's really an integer, and if so convert to a number with std::stoi.
From my answer and How do I check if a C++ string is an int?, I got this:
#include <fstream>
#include <iostream>
#include <string>
inline bool isInteger(const std::string & s)
{
if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false ;
char * p ;
strtol(s.c_str(), &p, 10) ;
return (*p == 0) ;
}
int main(void)
{
std::ifstream infile("thefile.txt");
if (infile.is_open()) {
int serial_number;
std::string model, terminator, serial_number_str;
while (infile >> terminator >> model >> serial_number_str)
{
if(terminator == "TERMINATOR" && isInteger(serial_number_str))
{
serial_number = std::stoi(serial_number_str);
std::cout << terminator << " " << model << " " << serial_number << "\n";
}
}
}
infile.close();
return 0;
}
which for a file of:
Georgioss-MacBook-Pro:~ gsamaras$ cat thefile.txt
TERMINATOR T-800 1
TERMINATOR T-1000 2
TERMINATOR T-800 3
TERMINATOR T-800 4
TORMONUTTUR T-800 1h6
abc 2
gives:
Georgioss-MacBook-Pro:~ gsamaras$ g++ main.cpp
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
TERMINATOR T-800 1
TERMINATOR T-1000 2
TERMINATOR T-800 3
TERMINATOR T-800 4
You can improve it further by using std::regex to check the format of model.

scanf() causing segmentation fault when previously working fine [closed]

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.

Resources