Hi, i'm still new to programming. I have been trying to learn C programming for basic command line tools in mac, however have come up against a problem. I have a unibody macbook and an imac G4. I wrote some code on my Macbook and it compiled fine and works on that however when I compile the same source file under gcc or xcode on my imac G4 (10.4.11) I get a segmentation fault. I have also tried compiling under Ubuntu linux however I also get a segmentation fault. I have not included any complex memory allocation and cannot figure what the problem is. I was hoping some seasoned developer may be able to point out in simplistic terms where abouts I have gone wrong.
Thanks in advance and any pointers would be appreciated (pun intended
)
Thanks in advance and any pointers would be appreciated (pun intended
Code:
/*
Darts Source Code is Licensed under a creative commons license. license shown below:
http://creativecommons.org/licenses/by-nc-sa/3.0/
All derivatives of this work to be attributed to thomas @ http://digital-focus.info
Email: thomas@digital-focus.info
TODO'S
- remove function scanf() and replace with fscanf() or fgets() once got to in book, to stop buffer overflow.
*/
#include <stdio.h>
// Flush Input Buffer
void Flush( void )
{
while ( getchar() != '\n' )
;
}
// Initiate main program
int main (int argc, const char * argv[])
{
// Global Variable Definition
int players;
int test1;
int test2;
int test3;
// Global Variable Definition (Arrays)
char name[players][15];
long int score[players];
// No of Players (Validation included)
test1 = 0;
while (test1 != 1)
{
printf ( "\nEnter number of players: " );
if ( scanf ( "%d", &players ) != 1 )
{
printf("Invalid Input");
Flush();
}
else
{
test1 = 1;
}
}
printf("\n");
// Declare loop counter i
int i;
i = 0;
// Loop for player names
while (++i < (players + 1))
{
printf ("Enter player %d's name: ", i);
scanf( "%14s", name[i-1]);
}
// Declare loop counter j and points for game
int j;
long int points;
// No of points for game (Validation included)
test2 = 0;
while (test2 != 1)
{
printf ( "\nEnter number of points to start from: " );
if ( scanf ( "%6ld", &points ) != 1 )
{
printf("Invalid Input");
Flush();
}
else
{
test2 = 1;
}
}
// Loop to set scores
for (j=0; j<players; j++)
{
score[j] = points;
}
// Declare loop counter j and variables for arithmetic
int k;
long int less;
long int temp;
// Loop to track scores until a score is 0 then release. (Validation included)
for (k=0; k<(players +1); k++)
{
temp = score[k];
test3 = 0;
while (test3 != 1)
{
printf ( "\n\n%s's turn - score: %ld\n\nPoints earned: " , name[k], score[k]);
if ( scanf ( "%6ld", &less ) != 1 || (temp - less) < 0)
{
printf("Invalid Input");
Flush();
}
else
{
test3 = 1;
}
}
score[k] = temp - less;
printf("\nNew Score: %ld\n",score[k]);
if (score[k] ==0 )
{
printf("\n\n\n%s has won!\n\n", name[k]);
break;
}
if (k== (players -1))
{
k=-1;
}
}
return 0;
}