1

I have written a type:

typedef struct
{
  int Tape[TAPE_SIZE];
  int *Head;
  int Tape_Count;
  int Loop_Start_Count;
} Tarpit;

I try to initialize this type with the following function:

void Tarpit_Initialize(Tarpit Tarpit)
{
  Tarpit.Tape_Count = 0;
  Tarpit.Loop_Start_Count = 0;

  int Index;
  for(Index = 0; Index < TAPE_SIZE; Index++)
    {
      Tarpit.Tape[Index] = INITIAL_SIZE;
    }
 }

However, it does not seem to work. If I run this:

Tarpit Foo;

Tarpit_Initialize(Foo);
printf("Tarpit Initialization Test: \n");

int index;
for(index = 0; index < TAPE_SIZE ; index++)
  {
    if(Foo.Tape[index] == INITIAL_SIZE)
      {
        printf("%d: %d \n", index, Foo.Tape[index]);
      }
    else
      {
        printf("%d: %d !ERROR \n", index, Foo.Tape[index]);
      }
  }

I get several non-zero values (I have set #define TAPE_SIZE 10000 and #define INITIAL_SIZE 0)

Moreover, if I run the test without running Tarpit_Initialize(Foo), I get exactly the same results. The initializer does not seem to work. Why/how could I implement it in an other way? I would like to set every element of Foo.Tape to zero.

Problem solved!

1
  • 1
    Tape_Length = sizeof(Tarpit.Tape); won't give you the size of the array, it'll give you the number of bytes required to store the array. Depending on the implementation, sizof an_int_array could be twice, four and, in theory, even eight times the number of elements. Instead use Tape_Length = sizeof Tarpit.Tape/sizeof *Tarpit_tape; -> lenght = total bytes/bytes per value of type Commented Jul 10, 2014 at 12:50

2 Answers 2

8

You are passing Tarpit by value:

void Tape_Initialize(Tarpit Tarpit)

That means it is only a copy of Tarpit. You have to pass a pointer to it to be able to modify it.

void Tape_Initialize(Tarpit* Tarpit)

and pass it as pointer (note the name of the function called!):

Tape_Initialize(&Foo);

and the use the -> operator to modify it. For instance:

Tarpit->Tape_Count = 0;

Moreover, as "Elias Van Ootegem" pointed out, you should not use sizeof(Tarpit.Tape) to get the size of the array but TAPE_LENGTH that you defined. Because sizeof() will give you a size in bytes not in elements.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Actually, however, what I posted was an older version of the functions that I pasted by accident (I was playing around with git). I am editing my post...
0

Have you checked the function u are calling ??

Its "Tarpit_Initialize(Foo);"

But the Function u are using it to initialize "void Tape_Initialize(Tarpit Tarpit)".

I think even what u have implemented should work fine .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.