user2012149
user2012149

Reputation: 13

Initialize int array in struct in C

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!

Upvotes: 1

Views: 387

Answers (2)

Baptiste Wicht
Baptiste Wicht

Reputation: 7663

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.

Upvotes: 8

pranathi
pranathi

Reputation: 393

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 .

Upvotes: 0

Related Questions