How can I run Raspberry pi's sample code on Code Blocks - c

I am working on a sample code of Raspberry PI 3(file path is: /opt/vc/src/hello_pi/hello_tiger). I want to run this sample code on Code Blocks. I created new project on Code Blocks and added main.c file and header file. I compiled this code, and I got an error. This was the error:
'rotaten' undeclared(first use in this function).
If I run the code on LXTerminal using the ./hello_tiger.bin command it works fine. But I want to run this code on Code Blocks or any compiler(such as monodevelop). The main.c file is given below.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <string.h>
#define UNREF(X) ((void)(X))
//#ifdef HG_FLAT_INCLUDES
#include "/opt/vc/src/hello_pi/libs/vgfont/VG/openvg.h"
#include "/opt/vc/src/hello_pi/libs/vgfont/VG/vgu.h"
#include "/opt/vc/src/hello_pi/libs/vgfont/EGL/egl.h"
/*
# include "openvg.h"
# include "vgu.h"
# include "egl.h" */
/*/#else
# include "VG/openvg.h"
# include "VG/vgu.h"
# include "EGL/egl.h"
#endif
*/
#include "tiger.h"
/*--------------------------------------------------------------*/
#ifdef __RASPBERRYPI__
static float rotateN = 0.0f;
#endif
const float aspectRatio = 612.0f / 792.0f;
int renderWidth = 0;
int renderHeight = 0;
EGLDisplay egldisplay;
EGLConfig eglconfig;
EGLSurface eglsurface;
EGLContext eglcontext;
/*--------------------------------------------------------------*/
typedef struct
{
VGFillRule m_fillRule;
VGPaintMode m_paintMode;
VGCapStyle m_capStyle;
VGJoinStyle m_joinStyle;
float m_miterLimit;
float m_strokeWidth;
VGPaint m_fillPaint;
VGPaint m_strokePaint;
VGPath m_path;
} PathData;
typedef struct
{
PathData* m_paths;
int m_numPaths;
} PS;
PS* PS_construct(const char* commands, int commandCount, const float* points, int pointCount)
{
PS* ps = (PS*)malloc(sizeof(PS));
int p = 0;
int c = 0;
int i = 0;
int paths = 0;
int maxElements = 0;
unsigned char* cmd;
UNREF(pointCount);
while(c < commandCount)
{
int elements, e;
c += 4;
p += 8;
elements = (int)points[p++];
assert(elements > 0);
if(elements > maxElements)
maxElements = elements;
for(e=0;e<elements;e++)
{
switch(commands[c])
{
case 'M': p += 2; break;
case 'L': p += 2; break;
case 'C': p += 6; break;
case 'E': break;
default:
assert(0); //unknown command
}
c++;
}
paths++;
}
ps->m_numPaths = paths;
ps->m_paths = (PathData*)malloc(paths * sizeof(PathData));
cmd = (unsigned char*)malloc(maxElements);
i = 0;
p = 0;
c = 0;
while(c < commandCount)
{
int elements, startp, e;
float color[4];
//fill type
int paintMode = 0;
ps->m_paths[i].m_fillRule = VG_NON_ZERO;
switch( commands[c] )
{
case 'N':
break;
case 'F':
ps->m_paths[i].m_fillRule = VG_NON_ZERO;
paintMode |= VG_FILL_PATH;
break;
case 'E':
ps->m_paths[i].m_fillRule = VG_EVEN_ODD;
paintMode |= VG_FILL_PATH;
break;
default:
assert(0); //unknown command
}
c++;
//stroke
switch( commands[c] )
{
case 'N':
break;
case 'S':
paintMode |= VG_STROKE_PATH;
break;
default:
assert(0); //unknown command
}
ps->m_paths[i].m_paintMode = (VGPaintMode)paintMode;
c++;
//line cap
switch( commands[c] )
{
case 'B':
ps->m_paths[i].m_capStyle = VG_CAP_BUTT;
break;
case 'R':
ps->m_paths[i].m_capStyle = VG_CAP_ROUND;
break;
case 'S':
ps->m_paths[i].m_capStyle = VG_CAP_SQUARE;
break;
default:
assert(0); //unknown command
}
c++;
//line join
switch( commands[c] )
{
case 'M':
ps->m_paths[i].m_joinStyle = VG_JOIN_MITER;
break;
case 'R':
ps->m_paths[i].m_joinStyle = VG_JOIN_ROUND;
break;
case 'B':
ps->m_paths[i].m_joinStyle = VG_JOIN_BEVEL;
break;
default:
assert(0); //unknown command
}
c++;
//the rest of stroke attributes
ps->m_paths[i].m_miterLimit = points[p++];
ps->m_paths[i].m_strokeWidth = points[p++];
//paints
color[0] = points[p++];
color[1] = points[p++];
color[2] = points[p++];
color[3] = 1.0f;
ps->m_paths[i].m_strokePaint = vgCreatePaint();
vgSetParameteri(ps->m_paths[i].m_strokePaint, VG_PAINT_TYPE, VG_PAINT_TYPE_COLOR);
vgSetParameterfv(ps->m_paths[i].m_strokePaint, VG_PAINT_COLOR, 4, color);
color[0] = points[p++];
color[1] = points[p++];
color[2] = points[p++];
color[3] = 1.0f;
ps->m_paths[i].m_fillPaint = vgCreatePaint();
vgSetParameteri(ps->m_paths[i].m_fillPaint, VG_PAINT_TYPE, VG_PAINT_TYPE_COLOR);
vgSetParameterfv(ps->m_paths[i].m_fillPaint, VG_PAINT_COLOR, 4, color);
//read number of elements
elements = (int)points[p++];
assert(elements > 0);
startp = p;
for(e=0;e<elements;e++)
{
switch( commands[c] )
{
case 'M':
cmd[e] = VG_MOVE_TO | VG_ABSOLUTE;
p += 2;
break;
case 'L':
cmd[e] = VG_LINE_TO | VG_ABSOLUTE;
p += 2;
break;
case 'C':
cmd[e] = VG_CUBIC_TO | VG_ABSOLUTE;
p += 6;
break;
case 'E':
cmd[e] = VG_CLOSE_PATH;
break;
default:
assert(0); //unknown command
}
c++;
}
ps->m_paths[i].m_path = vgCreatePath(VG_PATH_FORMAT_STANDARD, VG_PATH_DATATYPE_F, 1.0f, 0.0f, 0, 0, (unsigned int)VG_PATH_CAPABILITY_ALL);
vgAppendPathData(ps->m_paths[i].m_path, elements, cmd, points + startp);
i++;
}
free(cmd);
return ps;
}
void PS_destruct(PS* ps)
{
int i;
assert(ps);
for(i=0;i<ps->m_numPaths;i++)
{
vgDestroyPaint(ps->m_paths[i].m_fillPaint);
vgDestroyPaint(ps->m_paths[i].m_strokePaint);
vgDestroyPath(ps->m_paths[i].m_path);
}
free(ps->m_paths);
free(ps);
}
void PS_render(PS* ps)
{
int i;
assert(ps);
vgSeti(VG_BLEND_MODE, VG_BLEND_SRC_OVER);
for(i=0;i<ps->m_numPaths;i++)
{
vgSeti(VG_FILL_RULE, ps->m_paths[i].m_fillRule);
vgSetPaint(ps->m_paths[i].m_fillPaint, VG_FILL_PATH);
if(ps->m_paths[i].m_paintMode & VG_STROKE_PATH)
{
vgSetf(VG_STROKE_LINE_WIDTH, ps->m_paths[i].m_strokeWidth);
vgSeti(VG_STROKE_CAP_STYLE, ps->m_paths[i].m_capStyle);
vgSeti(VG_STROKE_JOIN_STYLE, ps->m_paths[i].m_joinStyle);
vgSetf(VG_STROKE_MITER_LIMIT, ps->m_paths[i].m_miterLimit);
vgSetPaint(ps->m_paths[i].m_strokePaint, VG_STROKE_PATH);
}
vgDrawPath(ps->m_paths[i].m_path, ps->m_paths[i].m_paintMode);
}
assert(vgGetError() == VG_NO_ERROR);
}
PS* tiger = NULL;
/*--------------------------------------------------------------*/
void render(int w, int h)
{
#ifndef __RASPBERRYPI__
if(renderWidth != w || renderHeight != h)
#endif
{
float clearColor[4] = {0,0,0,0};
float scale = w / (tigerMaxX - tigerMinX);
eglSwapBuffers(egldisplay, eglsurface); //force EGL to recognize resize
vgSetfv(VG_CLEAR_COLOR, 4, clearColor);
vgClear(0, 0, w, h);
vgLoadIdentity();
#ifdef __RASPBERRYPI__
vgTranslate(w * 0.5f, h * 0.5f);
vgRotate(rotateN);
vgTranslate(-w * 0.5f, -h * 0.5f);
#endif
vgScale(scale, scale);
vgTranslate(-tigerMinX, -tigerMinY + 0.5f * (h / scale - (tigerMaxY - tigerMinY)));
PS_render(tiger);
assert(vgGetError() == VG_NO_ERROR);
renderWidth = w;
renderHeight = h;
}
#ifndef __RASPBERRYPI__
eglSwapBuffers(egldisplay, eglsurface);
assert(eglGetError() == EGL_SUCCESS);
#endif
}
/*--------------------------------------------------------------*/
void init(NativeWindowType window)
{
static const EGLint s_configAttribs[] =
{
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_LUMINANCE_SIZE, EGL_DONT_CARE, //EGL_DONT_CARE
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_SAMPLES, 1,
EGL_NONE
};
EGLint numconfigs;
egldisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglInitialize(egldisplay, NULL, NULL);
assert(eglGetError() == EGL_SUCCESS);
eglBindAPI(EGL_OPENVG_API);
eglChooseConfig(egldisplay, s_configAttribs, &eglconfig, 1, &numconfigs);
assert(eglGetError() == EGL_SUCCESS);
assert(numconfigs == 1);
eglsurface = eglCreateWindowSurface(egldisplay, eglconfig, window, NULL);
assert(eglGetError() == EGL_SUCCESS);
eglcontext = eglCreateContext(egldisplay, eglconfig, NULL, NULL);
assert(eglGetError() == EGL_SUCCESS);
eglMakeCurrent(egldisplay, eglsurface, eglsurface, eglcontext);
assert(eglGetError() == EGL_SUCCESS);
tiger = PS_construct(tigerCommands, tigerCommandCount, tigerPoints, tigerPointCount);
}
/*--------------------------------------------------------------*/
void deinit(void)
{
PS_destruct(tiger);
eglMakeCurrent(egldisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
assert(eglGetError() == EGL_SUCCESS);
eglTerminate(egldisplay);
assert(eglGetError() == EGL_SUCCESS);
eglReleaseThread();
}
#include "/opt/vc/src/hello_pi/libs/vgfont/bcm_host.h"
int main(void)
{
uint32_t width, height;
bcm_host_init();
int s;
static EGL_DISPMANX_WINDOW_T nativewindow;
DISPMANX_ELEMENT_HANDLE_T dispman_element;
DISPMANX_DISPLAY_HANDLE_T dispman_display;
DISPMANX_UPDATE_HANDLE_T dispman_update;
VC_RECT_T dst_rect;
VC_RECT_T src_rect;
s = graphics_get_display_size(0 /* LCD */, &width, &height);
assert( s >= 0 );
dst_rect.x = 0;
dst_rect.y = 0;
dst_rect.width = width;
dst_rect.height = height;
src_rect.x = 0;
src_rect.y = 0;
src_rect.width = width << 16;
src_rect.height = height << 16;
dispman_display = vc_dispmanx_display_open( 0 /* LCD */);
dispman_update = vc_dispmanx_update_start( 0 );
dispman_element = vc_dispmanx_element_add ( dispman_update, dispman_display,
1/*layer*/, &dst_rect, 0/*src*/,
&src_rect, DISPMANX_PROTECTION_NONE, 0 /*alpha*/, 0/*clamp*/, 0/*transform*/);
nativewindow.element = dispman_element;
nativewindow.width = width;
nativewindow.height = height;
vc_dispmanx_update_submit_sync( dispman_update );
init(&nativewindow);
while (1) {
render(width, height);
rotateN += 1.0f; // compiler remarks this line
}
deinit();
return 0;
}
Compiler displays the remark at the bottom:

The definition of rotateN is visible to the compiler only if the macro __RASPBERRYPI__ is defined. As it is not defined in the code or any of the included header files or compiler options, you have this error.

Related

SDL with C - Blocks remains after being played

I have been working on a game that is a Stacker. Everything works fine, but after you have played and started over the blocks from the previous game still remain there.
Could anyone help me with this problem?
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <SDL/SDL_mixer.h>
#include <stdio.h>
#include <stdlib.h>
#define BASE_TIME_INTERVAL 80
#define SPEED_INCREASE 1.03
#define GAME_ROWS 15
#define GAME_COLUMNS 7
#define MIN(a, b) ((a < b) ? a : b)
#define MAX(a, b) ((a > b) ? a : b)
int array_matrix[GAME_ROWS][GAME_COLUMNS];
//void save();
int credit = 0;
int in = 0;
int out = 0;
int inGame = 0;
static SDL_Surface *screen;
//Sprites
static SDL_Surface *square;
static SDL_Surface *background;
static SDL_Surface *grid;
static SDL_Surface *main_ui;
static SDL_Surface *award;
//Text Credits Sprites
static SDL_Surface *credits;
static SDL_Surface *number;
//Sounds
Mix_Chunk *soundPlace = NULL;
Mix_Chunk *soundGameOver = NULL;
Mix_Chunk *soundCredit = NULL;
FILE * fptr;
void print_board() {
int i, j;
SDL_Rect src, dest;
for (i = 0; i < 15; i++) {
for (j = 0; j < 7 ; j++) {
if (array_matrix[i][j] == 1) {
src.x = 0;
src.y = 0;
src.w = 65;
src.h = 65;
dest.x = j * 67 + 227;
dest.y = i * 67 + 240;
dest.w = 65;
dest.h = 65;
SDL_BlitSurface(square, &src, screen, &dest);
}
}
}
}
void update_board(int x_pos, int length, int level) {
int underflow_ammt = length - 1;
int j;
if (x_pos < underflow_ammt)
length = length - (underflow_ammt - x_pos);
x_pos = MAX(0, x_pos-underflow_ammt);
for (j = 0; j < GAME_COLUMNS; j++)
array_matrix[GAME_ROWS - level][j] = 0;
for (j = x_pos; j < x_pos + length; j++) {
array_matrix[GAME_ROWS - level][MIN(j, GAME_COLUMNS-1)] = 1;
}
}
int get_new_length(int level) {
int i;
int length = 0;
for (i = 0; i < GAME_COLUMNS; i++) {
if (array_matrix[GAME_ROWS - level][i] == 1) {
length++;
if (level != 1) {
if (array_matrix[GAME_ROWS - (level - 1)][i] != 1) {
array_matrix[GAME_ROWS - level][i] = 0;
length--;
}
}
}
if ((level == 4 && length == 3) || (level == 10 && length == 2)) {
length--;
}
}
return length;
}
void draw_background(){
SDL_BlitSurface(background, NULL, screen, NULL);
SDL_BlitSurface(main_ui, NULL, screen, NULL);
SDL_BlitSurface(award, NULL, screen, NULL);
SDL_BlitSurface(grid, NULL, screen, NULL);
}
void draw_credits(){
SDL_Rect destCredits;
SDL_Rect destNumber;
switch (credit)
{
case 0:
number = IMG_Load("assets/0.png");
break;
case 1:
number = IMG_Load("assets/1.png");
break;
case 2:
number = IMG_Load("assets/2.png");
break;
case 3:
number = IMG_Load("assets/3.png");
break;
case 4:
number = IMG_Load("assets/4.png");
break;
case 5:
number = IMG_Load("assets/5.png");
break;
case 6:
number = IMG_Load("assets/6.png");
break;
case 7:
number = IMG_Load("assets/7.png");
break;
case 8:
number = IMG_Load("assets/8.png");
break;
case 9:
number = IMG_Load("assets/9.png");
break;
}
if (number == NULL) {
printf("Unable to load number png.\n");
}
destCredits.x = 300;
destCredits.y = 1300;
destNumber.x = 550;
destNumber.y = 1305;
SDL_BlitSurface(credits, NULL, screen, &destCredits);
SDL_BlitSurface(number, NULL, screen, &destNumber);
}
void game_loop() {
int time_delay = BASE_TIME_INTERVAL;
int left_or_right = 1;
int current_level = 1;
int length = 3;
int x_pos = 0;
int quit = 0;
int underflow_ammt = length - 1;
SDL_Event event;
while (!quit) {
while (SDL_PollEvent(&event)) {
switch(event.type) {
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_SPACE && inGame == 1) {
length = get_new_length(current_level);
underflow_ammt = length - 1;
if (current_level >= 15 || length == 0) {
Mix_PlayChannel( -1, soundGameOver, 0 );
inGame = 0;
time_delay = BASE_TIME_INTERVAL;
left_or_right = 1;
current_level = 1;
length = 3;
x_pos = 0;
underflow_ammt = length - 1;
}
else{
Mix_PlayChannel( -1, soundPlace, 0 );
current_level++;
time_delay = time_delay/SPEED_INCREASE;
}
}
if (event.key.keysym.sym == SDLK_2 && credit < 9){
credit++;
in++;
save();
Mix_PlayChannel( -1, soundCredit, 0 );
}
if (event.key.keysym.sym == SDLK_1 && credit > 0 && inGame == 0){
credit--;
out++;
save();
Mix_PlayChannel( -1, soundCredit, 0 );
inGame = 1;
}
if (event.key.keysym.sym == SDLK_ESCAPE){
quit = 1;
exit(0);
}
break;
case SDL_QUIT:
quit = 1;
exit(0);
break;
}
}
if (!quit) {
SDL_FillRect(screen, NULL, 0x000000);
if (x_pos >= GAME_COLUMNS + (underflow_ammt - 1))
left_or_right = -1;
if (x_pos <= 0)
left_or_right = 1;
update_board(x_pos, length, current_level);
draw_background();
if (inGame == 1)
print_board();
draw_credits();
SDL_Flip(screen);
x_pos = x_pos + left_or_right;
SDL_Delay(time_delay);
}
}
}
/*
void save(){
fptr = fopen("data.xml", "w");
fprintf(fptr,"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
fprintf(fptr,"<Data>\n");
fprintf(fptr," <credits>%d</credits>\n",credit);
fprintf(fptr," <IN>%d</IN>\n",in);
fprintf(fptr," <OUT>%d</OUT>\n",out);
fprintf(fptr,"</Data>\n");
fclose(fptr);
}
*/
void init(){
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
printf("Unable to initialize SDL: %s\n", SDL_GetError());
}
screen = SDL_SetVideoMode(768, 1366, 16, SDL_DOUBLEBUF | SDL_HWSURFACE | SDL_FULLSCREEN);
if (screen == NULL) {
printf("Unable to set video mode: %s\n", SDL_GetError());
}
int imgFlags = IMG_INIT_PNG;
if( !( IMG_Init( imgFlags ) & imgFlags ) )
{
printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
}
if (SDL_Init(SDL_INIT_AUDIO) < 0){
printf("Unable to set audio mode: %s\n", SDL_GetError());
}
//Initialize SDL_mixer
if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 )
printf( "SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError());
}
void loadMedia(){
background = IMG_Load("assets/background.png");
if (background == NULL)
printf("Unable to load background png.\n");
square = IMG_Load("assets/square.png");
if (square == NULL)
printf("Unable to load square png.\n");
credits = IMG_Load("assets/credits.png");
if (credits == NULL)
printf("Unable to load credits png.\n");
grid = IMG_Load("assets/grid.png");
if (grid == NULL)
printf("Unable to load grid png.\n");
main_ui = IMG_Load("assets/main_ui.png");
if (main_ui == NULL)
printf("Unable to load main_ui png.\n");
soundPlace = Mix_LoadWAV("assets/place.wav");
if(soundPlace == NULL)
printf( "Failed to load place sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
soundGameOver = Mix_LoadWAV("assets/gameover.wav");
if(soundGameOver == NULL)
printf( "Failed to load gameover sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
soundCredit = Mix_LoadWAV("assets/credit.wav");
if( soundCredit == NULL )
printf( "Failed to load credit sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
}
void close(){
SDL_FreeSurface(square);
SDL_FreeSurface(background);
SDL_FreeSurface(credits);
SDL_FreeSurface(grid);
SDL_FreeSurface(main_ui);
SDL_FreeSurface(number);
Mix_FreeChunk(soundPlace);
Mix_FreeChunk(soundGameOver);
Mix_FreeChunk(soundCredit);
Mix_Quit();
IMG_Quit();
SDL_Quit();
}
int main(int argc, char *argv[])
{
init();
loadMedia();
game_loop();
close();
return 0;
}
I using:
SDL 1.2.15
SDL_image 1.2.12
SDL_mixer 1.2.12

Struct/Malloc or Other? SIGSEGV Error

I have debugged and watched my "watch window" to get an idea where the problem was. It does not even finish the code though. During the test sequence to find the user inputted word, it fails. It has a SIGSEGV fault at the found function.
The code is meant to take in a word puzzle and then allow the user to find the words.
puzzleInput.txt:
M,N,O,S,L,I,W,E,R,E,L,Y,T,L,E,A,G,N
A,H,O,O,V,E,R,T,A,Y,L,O,R,V,E,N,N,A
D,F,D,R,O,O,S,E,V,E,L,T,O,N,O,M,I,M
I,N,T,P,M,H,I,E,G,D,I,L,O,O,C,O,D,U
S,O,N,L,I,J,Q,A,D,A,M,S,S,R,N,N,R,R
O,X,L,O,G,E,F,F,M,O,I,R,E,E,G,R,A,T
N,I,B,T,S,O,R,A,O,R,M,O,V,A,W,O,H,N
F,N,H,U,R,R,B,C,R,N,L,R,E,G,B,E,W,E
R,O,S,D,C,O,E,A,E,I,O,N,L,A,U,A,J,R
K,W,U,N,L,H,H,F,N,I,O,S,T,N,S,W,A,U
E,R,B,A,J,B,A,C,F,S,S,M,N,H,H,R,D,B
N,E,W,L,O,T,O,N,K,E,C,E,I,H,T,H,A,N
N,T,H,E,H,L,A,C,A,K,J,N,N,H,O,I,M,A
E,R,G,V,N,C,A,F,I,N,G,H,U,H,A,J,S,V
D,A,R,E,S,J,C,N,T,T,A,R,N,B,O,Y,A,E
Y,C,A,L,O,D,L,N,O,S,I,R,R,A,H,W,E,O
N,E,N,C,N,E,T,N,N,O,T,N,I,L,C,O,E,S
D,A,T,Y,Y,P,O,L,K,G,A,R,F,I,E,L,D,R
enter code here
code:
/* This program reads a puzzle from a file
and allows the user to define a word which
they want to find in the word puzzle.*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void fileNam(char[]);
char showMenu();
int fileData(char*);
void alphaArray();
void getUser();
void fileError(char*);
void findUserFirst();
int createString();
void found(int);
void notFound(char*);
void goToExit();
void display();
struct alphabet
{
int *A;int *B; int *C; int *D; int *E; int *F;
int *G; int *H; int *I; int *J; int *K; int *L; int *M;
int *N; int *O; int *P; int *Q; int *R; int *S;
int *T; int *U; int *V; int *W; int *X; int *Y; int *Z;
int a; int b; int c; int d; int e; int f; int g; int h; int i; int j; int k; int l; int m;
int n; int o; int p; int q; int r; int s; int t; int u; int v; int w; int x; int y; int z;
}fill;
struct user
{
struct alphabet* ptr;
int *attempt;
int testNum;
int columns;
int rows;
int userSize;
int puzzleSize;
char *puzzleArray;
char userWord[45];
}test;
int main()
{
int wordsFound = 0;
int fileErr = 0;
int wordF = 0;
char option;
char fileLoc[100] = {0};
do
{
fflush(stdin);
option = showMenu();
fflush(stdin);
if(fileErr == -1)
{
fileError(fileLoc);
}
switch(option)
{
case 'a':;
fileNam(fileLoc);
strcat(fileLoc,"\\puzzleInput.txt");
fileErr = fileData(fileLoc);
break;
case 'b':
display();
break;
case 'c':
getUser();
findUserFirst();
wordF = 0;
do{
wordF = createString();
if(wordF > 0)
{
found(wordF);
wordsFound++;
}
else
{
test.ptr;
}
}while(*test.attempt <= test.testNum);
if(wordF < -1)
notFound(fileLoc);
break;
case 'd':
goToExit(wordsFound);
break;
default:
printf("Invalid selection.\nPlease choose again.\n");
break;
}
}while(option != 'd');
return 0;
}
char showMenu()
{
char option;
printf("Choose one of the following:\n");
printf("\ta. Enter file location(full path)\n");
printf("\tb. Display the puzzle\n");
printf("\tc. Find a word\n");
printf("\td. Exit\n");
option = getchar();
return option;
}
void goToExit(int found)
{
printf("\nYou found %d words!\n", found);
if(found > 5)
{
printf("Awesome job! Come back to play again!");
}
else{
printf("Better luck next time!");
}
printf("Press any key to close window.");
getchar();
free(fill.A);free(fill.B); free(fill.C); free(fill.D); free(fill.E); free(fill.F);
free(fill.G); free(fill.H); free(fill.I); free(fill.J); free(fill.K); free(fill.L); free(fill.M);
free(fill.N); free(fill.O); free(fill.P); free(fill.Q); free(fill.R); free(fill.S);
free(fill.T); free(fill.U); free(fill.V); free(fill.W); free(fill.X); free(fill.Y); free(fill.Z);
free(test.puzzleArray);
}
void display()
{
int i, j, k = 0;
for(i=0; i <= test.columns; i++)
{
for(j=0; j <= test.rows; j++)
{
printf("%c, ", test.puzzleArray[k]);
k++;
}
printf("\n");
}
}
void fileNam(char fileLoc[])
{
printf("When entering file location, do not \n");
printf("include the file name.\nLOCATION:\n");
gets(fileLoc);
}
void fileError(char* fileName)
{
printf("There was an error with the file location");
printf(" that you typed in.\nPlease make sure file ");
printf("location and name are correct.\nIf name is wrong, ");
printf("please change the name of your file to match.\n");
printf("FILE LOCATION AND NAME: \"%s\"\n\n", fileName);
}
int fileData(char* fname)
{
int i = 0;
char curr;
FILE * fPtr;
fPtr = fopen(fname, "r");
char buffer[1000] = {0};
if(fPtr == NULL)//test if file opened
{
printf("There has been an error in opening %s!\n", fname);
return -1;
}
while (!feof(fPtr))
{
fgets(buffer, 1000, fPtr);
test.rows++;
}
rewind(fPtr);
while(fgetc(fPtr) >= 65 && fgetc(fPtr) <= 90)
{
test.puzzleSize++;
}
test.puzzleArray = (char*) malloc((test.puzzleSize) * sizeof(char));
printf("%d", test.puzzleSize);
rewind(fPtr);
i = 0;
while ((curr = fgetc(fPtr)) != EOF)
{
if(curr == ',' || curr == '\n')
{
if(curr == '\n')
test.columns++;
}
if(curr >= 65 && curr <= 90)
{
test.puzzleArray[i] = curr;
i++;
}
}
fclose(fPtr);
alphaArray();
return 0;
}
void alphaArray()
{
int i = 0;
char current = 0;
while(test.puzzleArray[i] != '\0')
{
current = test.puzzleArray[i];
switch(tolower(current))//accidentally coded lowercase, quick fix
{
case 'a':
fill.a++;
break;
case 'b':
fill.b++;
break;
case 'c':
fill.c++;
break;
case 'd':
fill.d++;
break;
case 'e':
fill.e++;
break;
case 'f':
fill.f++;
break;
case 'g':
fill.g++;
break;
case 'h':
fill.h++;
break;
case 'i':
fill.i++;
break;
case 'j':
fill.j++;
break;
case 'k':
fill.k++;
break;
case 'l':
fill.l++;
break;
case 'm':
fill.m++;
break;
case 'n':
fill.n++;
break;
case 'o':
fill.o++;
break;
case 'p':
fill.p++;
break;
case 'q':
fill.q++;
break;
case 'r':
fill.r++;
break;
case 's':
fill.s++;
break;
case 't':
fill.t++;
break;
case 'u':
fill.u++;
break;
case 'v':
fill.v++;
break;
case 'w':
fill.w++;
break;
case 'x':
fill.x++;
break;
case 'y':
fill.y++;
break;
case 'z':
fill.z++;
break;
default: printf("\n");
break;
}
i++;
}
fill.A = (int *)malloc(sizeof(int)*fill.a); fill.B = (int *)malloc(sizeof(int)*fill.b);
fill.C = (int *)malloc(sizeof(int)*fill.c); fill.D = (int *)malloc(sizeof(int)*fill.d);
fill.E = (int *)malloc(sizeof(int)*fill.e); fill.F = (int *)malloc(sizeof(int)*fill.f);
fill.G = (int *)malloc(sizeof(int)*fill.g); fill.H = (int *)malloc(sizeof(int)*fill.h);
fill.I = (int *)malloc(sizeof(int)*fill.i); fill.J = (int *)malloc(sizeof(int)*fill.j);
fill.K = (int *)malloc(sizeof(int)*fill.k); fill.L = (int *)malloc(sizeof(int)*fill.l);
fill.M = (int *)malloc(sizeof(int)*fill.m); fill.N = (int *)malloc(sizeof(int)*fill.n);
fill.O = (int *)malloc(sizeof(int)*fill.o); fill.P = (int *)malloc(sizeof(int)*fill.p);
fill.Q = (int *)malloc(sizeof(int)*fill.q); fill.R = (int *)malloc(sizeof(int)*fill.r);
fill.S = (int *)malloc(sizeof(int)*fill.s); fill.T = (int *)malloc(sizeof(int)*fill.t);
fill.U = (int *)malloc(sizeof(int)*fill.u); fill.V = (int *)malloc(sizeof(int)*fill.v);
fill.W = (int *)malloc(sizeof(int)*fill.w); fill.X = (int *)malloc(sizeof(int)*fill.x);
fill.Y = (int *)malloc(sizeof(int)*fill.y); fill.Z = (int *)malloc(sizeof(int)*fill.z);
fill.a = 0;fill.b =0; fill.c =0; fill.d =0; fill.e =0; fill.f =0;
fill.g =0; fill.k =0; fill.o =0; fill.s =0; fill.w =0;
fill.h =0; fill.l =0; fill.p =0; fill.t =0; fill.x =0;
fill.i =0; fill.m =0; fill.q =0; fill.u =0; fill.y =0;
fill.j =0; fill.n =0; fill.r =0; fill.v =0; fill.z =0;
i = 0;
while(test.puzzleArray[i] != '\0')
{
current = test.puzzleArray[i];
switch(tolower(current))//accidentally coded lowercase, quick fix
{
case 'a':
fill.A[fill.a] = i;
fill.a++;
break;
case 'b':
fill.B[fill.b] = i;
fill.b++;
break;
case 'c':
fill.C[fill.c] = i;
fill.c++;
break;
case 'd':
fill.D[fill.d] = i;
fill.d++;
break;
case 'e':
fill.E[fill.e] = i;
fill.e++;
break;
case 'f':
fill.F[fill.f] = i;
fill.f++;
break;
case 'g':
fill.G[fill.g] = i;
fill.g++;
break;
case 'h':
fill.H[fill.h] = i;
fill.h++;
break;
case 'i':
fill.I[fill.i] = i;
fill.i++;
break;
case 'j':
fill.J[fill.j] = i;
fill.j++;
break;
case 'k':
fill.K[fill.k] = i;
fill.k++;
break;
case 'l':
fill.L[fill.l] = i;
fill.l++;
break;
case 'm':
fill.M[fill.m] = i;
fill.m++;
break;
case 'n':
fill.N[fill.n] = i;
fill.n++;
break;
case 'o':
fill.O[fill.o] = i;
fill.o++;
break;
case 'p':
fill.P[fill.p] = i;
fill.p++;
break;
case 'q':
fill.Q[fill.q] = i;
fill.q++;
break;
case 'r':
fill.R[fill.r] = i;
fill.r++;
break;
case 's':
fill.S[fill.s] = i;
fill.s++;
break;
case 't':
fill.T[fill.t] = i;
fill.t++;
break;
case 'u':
fill.U[fill.u] = i;
fill.u++;
break;
case 'v':
fill.V[fill.v] = i;
fill.v++;
break;
case 'w':
fill.W[fill.w] = i;
fill.w++;
break;
case 'x':
fill.X[fill.x] = i;
fill.x++;
break;
case 'y':
fill.Y[fill.y] = i;
fill.y++;
break;
case 'z':
fill.Z[fill.z] = i;
fill.z++;
break;
default: printf("\n");
break;
}
i++;
}
}
void getUser()
{
test.testNum = 0;
test.userWord[45] = '\0';
test.ptr = 0;
printf("\nWhat word would you like to search for?\n");
scanf("%s", test.userWord);
test.userSize = strlen(test.userWord);
}
void findUserFirst()
{
switch(tolower(test.userWord[0]))
{
case 'a':
test.attempt = &fill.A[0];
test.testNum = fill.a;
break;
case 'b':
test.attempt = &fill.B[0];
test.testNum = fill.b;
break;
case 'c':
test.attempt = &fill.C[0];
test.testNum = fill.c;
break;
case 'd':
test.attempt = &fill.D[0];
test.testNum = fill.d;
break;
case 'e':
test.attempt = &fill.E[0];
test.testNum = fill.e;
break;
case 'f':
test.attempt = &fill.F[0];
test.testNum = fill.f;
break;
case 'g':
test.attempt = &fill.G[0];
test.testNum = fill.g;
break;
case 'h':
test.attempt = &fill.H[0];
test.testNum = fill.h;
break;
case 'i':
test.attempt = &fill.I[0];
test.testNum = fill.i;
break;
case 'j':
test.attempt = &fill.J[0];
test.testNum = fill.j;
break;
case 'k':
test.attempt = &fill.K[0];
test.testNum = fill.k;
break;
case 'l':
test.attempt = &fill.L[0];
test.testNum = fill.l;
break;
case 'm':
test.attempt = &fill.M[0];
test.testNum = fill.m;
break;
case 'n':
test.attempt = &fill.N[0];
test.testNum = fill.n;
break;
case 'o':
test.attempt = &fill.O[0];
test.testNum = fill.o;
break;
case 'p':
test.attempt = &fill.P[0];
test.testNum = fill.p;
break;
case 'q':
test.attempt = &fill.Q[0];
test.testNum = fill.q;
break;
case 'r':
test.attempt = &fill.R[0];
test.testNum = fill.r;
break;
case 's':
test.attempt = &fill.S[0];
test.testNum = fill.s;
break;
case 't':
test.attempt = &fill.T[0];
test.testNum = fill.t;
break;
case 'u':
test.attempt = &fill.U[0];
test.testNum = fill.u;
break;
case 'v':
test.attempt = &fill.V[0];
test.testNum = fill.v;
break;
case 'w':
test.attempt = &fill.W[0];
test.testNum = fill.w;
break;
case 'x':
test.attempt = &fill.X[0];
test.testNum = fill.x;
break;
case 'y':
test.attempt = &fill.Y[0];
test.testNum = fill.y;
break;
case 'z':
test.attempt = &fill.Z[0];
test.testNum = fill.z;
break;
default: printf("\n");
}
}
int createString()
{
int i = 0, upRoom = 0, rightRoom = 0;
int leftRoom = 0, downRoom = 0;
int columnPos = 0, rowPos = 0;
int arPos = 0;
int moveup = 0, moveupr = 0;
int moveupl = 0, mover = 0;
int movel = 0, moved = 0;
int movedr = 0, movedl = 0;
char up[45];
char upRight[45];
char right[45];
char downRight[45];
char down[45];
char downLeft[45];
char left[45];
char upLeft[45];
arPos = *test.attempt;
columnPos = arPos / test.columns;
rowPos = arPos % test.rows;
upRoom = test.columns/2 - columnPos;
downRoom = test.columns/2 - columnPos;
rightRoom = test.rows/2 - rowPos;
leftRoom = test.rows/2 - rowPos;
moveup = -(test.rows);
moveupr = (test.rows - 1) * (-1),
moveupl = -(test.rows + 1);
mover = 1;
movel = 1;
moved = test.rows,
movedr = 1 * (test.rows + 1);
movedl = 1 * (test.rows - 1);
for(i=0; i < test.userSize; i++)
{
if(rightRoom >= 0)
{
right[i] = test.puzzleArray[arPos + i*mover];
if(upRoom >= 0)
upRight[i] = test.puzzleArray[arPos + i*moveupr];
if(downRoom >= 0)
downRight[i] = test.puzzleArray[arPos + i*movedr];
}
if(leftRoom >= 0)
{
left[i] = test.puzzleArray[arPos - movel];
if(upRoom >= 0)
upLeft[i] = test.puzzleArray[arPos + i*moveupl];
if(downRoom >= 0)
downLeft[i] = test.puzzleArray[arPos + i*movedl];
}
if(upRoom >= 0)
up[i] = test.puzzleArray[arPos + i*moveup];
if(downRoom >= 0)
down[i] = test.puzzleArray[arPos + i*moved];
}
for(i = 0; i < test.userSize; i++)
{
if(strcmp(up, test.userWord) == 0)
return 1;
if(strcmp(upRight, test.userWord) == 0)
return 2;
if(strcmp(right, test.userWord) == 0)
return 3;
if(strcmp(downRight, test.userWord) == 0)
return 4;
if(strcmp(down, test.userWord) == 0)
return 5;
if(strcmp(downLeft, test.userWord) == 0)
return 6;
if(strcmp(left, test.userWord) == 0)
return 7;
if(strcmp(upLeft, test.userWord) == 0)
return 8;
else
return -1;
}
return -1;
}
void found(int style)
{
int pos = 0, movement = 0;
int i, j, k = 0;
char *cpyPuzzle;
cpyPuzzle = (char*) malloc((test.puzzleSize) * sizeof(char));
strcpy(cpyPuzzle, test.puzzleArray);
switch(style){
case 1:
movement = test.rows;
break;
case 2:
movement = test.rows - 1;
break;
case 3:
movement = 1;
break;
case 4:
movement = test.rows + 1;
break;
case 5:
movement = test.rows;
break;
case 6:
movement = test.rows - 1;
break;
case 7:
movement = 1;
break;
case 8:
movement = test.rows + 1;
break;
}
for(i = 0; i < test.puzzleSize; i++)
{
cpyPuzzle[i] = '~';
}
for(i=0; i < test.userSize; i++)
{
pos = test.attempt + (i*movement);
cpyPuzzle[pos] = test.userWord[i];
}
for(i=0; i < test.columns; i++)
{
for(j=0; j < test.rows; j++)
{
printf("%c, ", cpyPuzzle[k]);
k++;
}
printf("\n");
}
free(cpyPuzzle);
}
void notFound(char *fileN)
{
printf("In file %s %c was not found.\n", test.userWord, fileN);
printf("You can try finding another word");
printf(" by pressing the option to show puzzle and\n");
printf("then the option to find a word, once you've found one.\n");
}
(Posted on behalf of the OP).
SOLVED! - the error was I was not dereferencing and then referencing a pointer.

error : expected identifier or '(' in global variable

I got this errror during compile processing.
I already saw this error in this site before, I think this error can occur when the ; or something are in wrong place. but I can't find.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#define MAX 80
typedef struct assemble
{
int op;
int ni;
int xbpe;
int addr;
}Assemble;
void get_token(char *bp);
int hTod(char *dp);
int bTod(char *dp);
void codeBreak(char *cp);
void result(int t);
Assemble asm;
int type;
int main()
{
FILE *fp;
char buf[MAX];
if( (fp = fopen("inst.txt","r")) == NULL ){
fprintf(stderr, "file not found...\n"); exit(1);
}
while(fgets(buf,sizeof(buf),fp) != NULL){
get_token(buf);
}
fclose(fp);
return 0;
}
void get_token(char *bp)
{
char *cp;
int i = 1;
for(cp=strtok(bp, " \t\n"); cp != NULL; )
{
if( (*(cp+0) == '0') && (*(cp+1) == 'x') )
{
if( i == -1 )
asm.addr = hTod(cp);
if( i == 1)
asm.op = hTod(cp);
i *= -1;
}
else
{
codeBreak(cp);
}
cp = strtok(NULL, " \t\n");
}
result(type);
}
void codeBreak(char *cp)
{
if ( strlen(cp) == 2 ) // ni 판단
{
asm.ni = bTod(cp);
}
else if( strlen(cp) == 1 )
{
asm.xbpe = bTod(cp)*pow(2,3);
type = 1;
}
else if( strlen(cp) == 4 )
{
if( *(cp+3) == '1')
{
asm.xbpe = bTod(cp);
type = 2;
}
else
{
asm.xbpe = bTod(cp);
type = 3;
}
}
}
void result(int t)
{
switch(t)
{
case 1 : printf("0x%x%x\n", (asm.op+asm.ni), asm.addr); break;
case 2 : printf("0x%x%x%.5x\n", (asm.op+asm.ni), asm.xbpe, asm.addr); break;
case 3 : printf("0x%x%x%.3x\n", (asm.op+asm.ni), asm.xbpe, asm.addr); break;
default : break;
}
}
/* Hex to decimal */
int hTod(char *dp)
{
int i;
int dec = 0;
for( i=2 ; i < strlen(dp) ; i++)
{
switch (*(dp+i))
{
case 'a' : *(dp+i) = 58; break;
case 'b' : *(dp+i) = 59; break;
case 'c' : *(dp+i) = 60; break;
case 'd' : *(dp+i) = 61; break;
case 'e' : *(dp+i) = 62; break;
case 'f' : *(dp+i) = 63; break;
}
dec += (*(dp+i)-48) * pow( 16, (strlen(dp)-(i+1)));
}
return dec;
}
/* binary to decimal*/
int bTod(char *dp)
{
int i;
int dec = 0;
for( i = 0; i < strlen(dp) ; i++)
{
dec += (*(dp+i)-48) * pow( 2, (strlen(dp) - (i+1)));
}
return dec;
}
asm is a keyword. Instead of
Assemble asm;
use something different, such as:
Assemble asm1;
The problem reported by the compiler is different though. You seem to have used
ASSEMBLY asm;
in the code you compiled.

C - segmentation fault on long running while loop

I wrote small daemon for rotating screen on Thinkpad X41 convertible laptop using built-in motion sensor (used by harddisk active protection system) or manually by button. Program works very well, but after some amount of time (5 to 15 minutes) will crash with segfault.
I know there are lot of scripts on the internet to do this written in bash or python, but none of them suit my needs and vision how should program work.
I know that for example mentioned bash is probably better for this, but I have zero experiences with it compared to C In which I have at least minimal basic experiences from few high school lessons, so I choose this.
here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define TRUE 1
#define FALSE 0
#define NIL -1
#define XRANDR_GREP_COMMAND "xrandr -q --verbose|grep LVDS1|cut -b37-37"
#define DAEMON_LOCK_FILE "/dev/shm/thinkrotate.lock"
#define DAEMON_STATE_FILE "/dev/shm/thinkrotate.st"
#define SWIVEL_STATE_FILE "/sys/devices/platform/thinkpad_acpi/hotkey_tablet_mode"
#define GYRO_STATE_FILE "/sys/devices/platform/hdaps/position"
#define BUBBLE_TERMINATED "notify-send 'Ukončenie programu' 'ThinkRotate démon dostal príkaz na ukončenie'"
#define BUBBLE_SWIVEL_DOWN "notify-send 'Notebook v tablet móde' 'Veko bolo sklopené, aktivovaná automatická rotácia'"
#define BUBBLE_SWIVEL_UP "notify-send 'Notebook v štandartnom režime' 'Rotácia je deaktivovaná'"
#define BUBBLE_RETURN_POSITION "notify-send 'Automatická rotácia zapnutá' 'Pre vypnutie automatickej rotácie obrazu stlačte tlačítko rotácie.'"
#define BUBBLE_START_MANUAL_ROTATION "notify-send 'Automatická rotácia vypnutá' 'Rotácia bude zapnutá znovu až pri návrate do tejto polohy, dovtedy na otáčanie obrazu používajte tlačidlo.'"
#define SWIVEL_DOWN_COMMANDS ""
#define SWIVEL_UP_COMMANDS ""
#define WIDTH_COMMANDS ""
#define HEIGHT_COMMANDS ""
int get_lock(void) {
int fdlock;
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 1;
if((fdlock = open(DAEMON_LOCK_FILE, O_WRONLY|O_CREAT, 0666)) == -1) { return 0; }
if(fcntl(fdlock, F_SETLK, &fl) == -1) { return 0; }
return 1;
}
int next_rotation(int direction) {
int next;
int pos;
pos = current_pos();
if (direction == 1) {
switch (pos) {
case 0:
next = 1;
break;
case 1:
next = 2;
break;
case 2:
next = 3;
break;
case 3:
next = 0;
break;
}
} else if (direction == 2) {
switch (pos) {
case 0:
next = 3;
break;
case 1:
next = 0;
break;
case 2:
next = 1;
break;
case 3:
next = 2;
break;
}
}
return next;
}
int current_pos(void) {
FILE *frotpos;
char rotpos;
int pos;
frotpos = popen(XRANDR_GREP_COMMAND, "r");
fscanf(frotpos, "%c", &rotpos);
fclose(frotpos);
switch (rotpos) {
case 110:
pos = 0;
break;
case 108:
pos = 1;
break;
case 105:
pos = 2;
break;
case 114:
pos = 3;
break;
}
return pos;
}
void rotate(int poz) {
char buff[32];
if ((poz == 2)||(poz == 0)) {
system(WIDTH_COMMANDS);
} else {
system(HEIGHT_COMMANDS);
}
sprintf(buff, "xrandr -o %i", poz);
system(buff);
}
int main(int argc, char *argv[]) {
if(!get_lock()) {
if (argc >= 2) {
int cmd;
FILE *fparams;
fparams = fopen(DAEMON_STATE_FILE, "w");
if (!strncmp(argv[1], "r", 1)) { cmd = 1; }
else if (!strncmp(argv[1], "l", 1)) { cmd = 2; }
else if (!strncmp(argv[1], "k", 1)) { cmd = 0; }
fprintf(fparams, "%i", cmd);
fclose(fparams);
}
return 1;
}
int autorotate = TRUE;
int prevmode = NIL;
FILE *fstate;
int tabletmode;
FILE *fgyrovals;
char gyroval_x[5];
char gyroval_y[5];
int x;
int y;
FILE *fargs;
int argum = NIL;
int next_p;
int prev_p = current_pos();
int last_auto_p = NIL;
while (TRUE) {
fstate = fopen(SWIVEL_STATE_FILE, "r");
fscanf(fstate, "%d", &tabletmode);
if (fargs = fopen(DAEMON_STATE_FILE, "r")) {
if (fscanf(fargs, "%d", &argum) == NIL) { argum = NIL; }
}
fargs = fopen(DAEMON_STATE_FILE, "w");
fclose(fargs);
fclose(fstate);
if (argum == 0) {
system(BUBBLE_TERMINATED);
return 1;
}
if (prevmode != tabletmode) {
if (tabletmode) {
system(BUBBLE_SWIVEL_DOWN);
system(SWIVEL_DOWN_COMMANDS);
} else {
system(BUBBLE_SWIVEL_UP);
system(SWIVEL_UP_COMMANDS);
rotate(0);
}
}
if (tabletmode) {
if (argum == 1 || argum == 2) {
next_p = next_rotation(argum);
if (next_p == last_auto_p) {
rotate(next_p);
autorotate = TRUE;
last_auto_p = NIL;
system(BUBBLE_RETURN_POSITION);
} else if ((autorotate)&&(current_pos() == last_auto_p)) {
autorotate = FALSE;
system(BUBBLE_START_MANUAL_ROTATION);
} else {
if (autorotate) {
system(BUBBLE_START_MANUAL_ROTATION);
last_auto_p = current_pos();
} else {
rotate(next_p);
}
autorotate = FALSE;
}
}
if (autorotate) {
fgyrovals = fopen(GYRO_STATE_FILE, "r");
fscanf(fgyrovals, "(%4[^,], %4[^)]", &gyroval_x, &gyroval_y);
fclose(fgyrovals);
x = atoi(gyroval_x);
y = atoi(gyroval_y) * (-1);
if (y < 465) {
if (x < 210) {
next_p = 1;
} else if (x > 425) {
next_p = 3;
} else {
next_p = 2;
}
} else if (y > 525) {
if (x < 210) {
next_p = 1;
} else if (x > 425) {
next_p = 3;
} else {
next_p = 0;
}
} else {
if (x < 305) {
next_p = 1;
} else if (x > 345) {
next_p = 3;
}
}
if (next_p != prev_p) {
rotate(next_p);
prev_p = next_p;
}
}
} else {
if (argum == 1 || argum == 2) {
system(BUBBLE_SWIVEL_UP);
}
}
prevmode = tabletmode;
sleep(1);
}
return 0;
}
Thanks to comment of user "inspired". Now the program is running more than a hour without segfault.
if (fargs = fopen(DAEMON_STATE_FILE, "r")) {
if (fscanf(fargs, "%d", &argum) == NIL) { argum = NIL; }
fclose(fargs);
}
fargs = fopen(DAEMON_STATE_FILE, "w");
fclose(fargs);
As said, file should be closed before opened next time for writing.

error using structs, C

i am getting the error "a3.c:221:20: error: storage size of ‘gold’ isn’t known" for all 4 of my item structs. My code is as follows:
void parser(int argc, char **argv)
{
FILE * rooms;
char * theString;
char * theToken;
int numberElements;
int side;
int k;
int placeInt;
int posX;
int posY;
char a[ROOM_STRING_LENGTH];
numberElements = 0;
rooms = fopen(argv[1], "r");
if(rooms == NULL)
{
printf("error opening file\n");
}
while(fgets(a, ROOM_STRING_LENGTH, rooms) != NULL)
{
theString = malloc((sizeof(char)*(strlen(a)+1)));
strcpy(theString, a);
for(theToken = strtok(theString, " "); theToken; theToken = strtok(NULL, " "))
{
printf("the next token: %s\n", theToken);
if(theToken[0] == '1')
{
}
if(theToken[0] == 'd')
{
switch(theToken[1])
{
case 'e':
{
side = 1;
placeInt = theToken[2] - '0';
printf("the side: %d, the place: %d\n", side, placeInt);
break;
}
case 'w':
{
side = 2;
placeInt = theToken[2] - '0';
printf("the side: %d, the place: %d\n", side, placeInt);
break;
}
case 's':
{
side = 3;
placeInt = theToken[2] - '0';
printf("the side: %d, the place: %d\n", side, placeInt);
break;
}
case 'n':
{
side = 4;
placeInt = theToken[2] - '0';
printf("the side: %d, the place: %d\n", side, placeInt);
break;
}
default:
{
break;
}
}
}
else if(theToken[0] == 'g' || theToken[0] == 'm' || theToken[0] == 'p' || theToken[0] == 'h')
{
k = 0;
while(k <= (strlen(theToken)))
{
switch(theToken[k])
{
case 'g':
posY = theToken[1] - '0';
posX = theToken[3] - '0';
struct item gold;
gold.Xposition = posX;
gold.Yposition = posY;
printf("the y position: %d, the x position: %d\n", posY, posX);
break;
case 'm':
posY = theToken[1] - '0';
posX = theToken[3] - '0';
struct item monster;
monster.Xposition = posX;
monster.Yposition = posY;
printf("the y position: %d, the x position: %d\n", posY, posX);
break;
case 'p':
posY = theToken[1] - '0';
posX = theToken[3] - '0';
struct item potion;
potion.Xposition = posX;
potion.Yposition = posY;
printf("the y position: %d, the x position: %d\n", posY, posX);
break;
case 'h':
posY = theToken[1] - '0';
posX = theToken[3] - '0';
struct item hero;
hero.Xposition = posX;
hero.Yposition = posY;
printf("the y position: %d, the x position: %d\n", posY, posX);
break;
}
k++;
}
}
else if(theToken == NULL)
{
printf("end of file");
}
numberElements++;
}
if(theToken == NULL)
{
printf("You've reached the end of the line\n");
}
printf("%d\n", numberElements);
}
free(theString);
fclose(rooms);
}
struct item
{
int Xposition;
int Yposition;
};
Also, I was wondering how i would go about accessing the information i just stored into those structs in a different function.
As keltar and nonsensickle already mentioned, you have to define struct item before you can use an instance of it:
struct item { int x; int y; }; // this must come first
// ...
struct item item1 {4, 2};
You could, however, use a pointer before the definition, as long as you have already declared the struct:
struct item; // declaration, no definition
// ...
struct item *pitem1;
// ...
struct item { int x; int y; }; // defined later
To use a struct's members in another function, you could pass either a struct or a struct* to that function:
void use_struct (struct item i)
{
int a = i.x, b = i.y;
}
void use_struct_pointer (struct item *pi)
{
int a = pi->x, b = pi->y;
}
int main()
{
struct item i {4, 2};
use_struct(i);
use_struct_pointer(&i);
return 0;
}

Resources