1

I created a C extension, the purpose of which is to determine if a series of cards will result in a straight or not. The example might be a little more complicated than necessary to show the issue, but essentially foo should be storing inside of it all the cards that were evaluated (each with an assigned index). So bar should have an entirely separate set of cards and indexes. But it seems that when I start assigning cards to bar, it is overwriting foo. I'll include my code below in case I am doing something wrong with pointers.

>> require 'ext/straight_count' #=> true                                                                                            

>> foo = EV::StraightCount.new; 
>> foo.evaluate(6,0); 
>> foo.evaluate(5,1); 
>> foo.evaluate(4,2); 
>> foo.evaluate(3,3); 
>> foo.evaluate(3,4); 
>> foo.evaluate(3,5); 
>> foo.evaluate(3,6); 
>> foo.straight_cards
=> []

>> bar = EV::StraightCount.new; 
>> bar.evaluate(11,0); 
>> bar.evaluate(10,1); 
>> bar.evaluate(9,2); 
>> bar.evaluate(8,3); 
>> bar.evaluate(7,4); 
>> bar.evaluate(2,5); 
>> bar.evaluate(2,6); 
>> bar.straight_cards
=> [11, 10, 9, 8, 7]

>> foo.evaluate(3,6); 
>> foo.straight_cards 
=> [11, 10, 9, 8, 7]

.h file

static int *pCards;
static int *pSortedCards[NUM_CARDS];
static int i, rMadeHandIndex, cCards[NUM_CARDS], begin_straight, end_straight;

VALUE rIsFound = Qfalse;

static VALUE EV, StraightCount;

static void reset_score();
static VALUE found();
static VALUE score();
static VALUE straight_cards();
Matheus Moreira
  • 17,106
  • 3
  • 68
  • 107
Jeremy Smith
  • 14,727
  • 19
  • 67
  • 114

1 Answers1

4

pSortedCards appears to be a global. Hence the reason why you have shared state.

Arafangion
  • 11,517
  • 1
  • 40
  • 72
  • I don't understand, I included my .h file, how are these variables global? – Jeremy Smith Jun 26 '11 at 15:13
  • Because that's what they are. :) – Arafangion Jun 26 '11 at 15:29
  • Ok, I did some reading and found that anything declared in a .h file is global. Did not know this. Thanks. – Jeremy Smith Jun 26 '11 at 15:30
  • 3
    The reason they are global is because they are in global scope, not because they are in a .h file. (The way .h files are used in C projects is merely a convention, the C compiler does not really distinguish between .h and .c files). The distinction is very important because you can't define things more than once. (You can declare them, as is the case with your functions, but you can only implement the function once). I suggest buying an actual C book, rather than websites. – Arafangion Jun 26 '11 at 15:33