Home > Mobile >  array value is not incremented
array value is not incremented

Time:10-04

I am writing a code and i hope this summon my problem. Any help is appreciated>

I created an array by:

    intermediateBinCounts = (int *)malloc(bin_count * thread_count * sizeof(int));

and want it to increment value in another function:

  for(int i=privateStartingIndex; i<privateEndingIndex; i  ){
    int returnedBinIndex = findBin(data[i]);
    int intermBinCountIndex = (threadIndex*bin_count) returnedBinIndex;
    intermediateBinCounts[intermBinCountIndex]  ;
    printf("\nthis is value %d\n", intermediateBinCounts[intermBinCountIndex]);
}

intermBinCountIndex is integer which is returned from the function and their value in my case are among 0, 1, 2, 3 only.

but my printf is returning:

this is value -1163005938

this is value -1163005937

this is value -1163005938

I don't know if my question is able to articulate my issue if it is not able to please let me know so that I could edit it again my best.

I want that intermediateBinCounts to be initialized to zero and increment the value at that index which value is returned from the function call i.e findBin.

CodePudding user response:

This declares a pointer to int, without already defining it, this is for headers
(though doing this implies global variables which many users recommend against):

extern int* pointer;

This defines that pointer, without initialising it; this is for exactly one code file:

int* pointer;

This defines and initialises the pointer; use it instead of above:

int* pointer=NULL;

This allocates some memory to the pointer:

pointer = malloc(sizeof(int));

This initialises the allocated memory:

*pointer=0;

This uses the initialised value pointed to by the pointer and increments it; doing this before above means undefined behaviour and would explain your unexpected values:

*pointer = *pointer 1;

Please check your code for what you are actually doing when.
Most likely you did not do the initialising.

CodePudding user response:

I want that intermediateBinCounts to be initialized to zero

Well, you don't want that. intermediateBinCounts is a pointer and you want to set it to the value returned by malloc.

What you want to set to zero is the memory that intermediateBinCounts points to!

You can use a simple loop after the malloc- like:

int * intermediateBinCounts = malloc(bin_count * thread_count * sizeof(int));
for (int i=0; i < bin_count * thread_count;   i)
{
    intermediateBinCounts[i] = 0;
}

or use calloc instead of malloc as calloc zero initialize the allocated memory:

int* intermediateBinCounts = calloc(bin_count * thread_count, sizeof(int));
  • Related