-1

How do i Initialize whole block of an array in c on the heap

int* a[102875] = {0xff, 0xff..........};

Like the followed example

I Tried also other ways to initialize array Like:

myArray = (int*)calloc(102875, sizeof(int));

it worked fine but I can't initialize whole block of memory.

273K
  • 29,503
  • 10
  • 41
  • 64
The BOSS
  • 1
  • 1
  • 1
    The first line can't compile, since 0xff is not a pointer `int*` – 273K Dec 03 '22 at 23:29
  • The cast to `int *` is unnecessary. See this question for further information: [Do I cast the result of malloc?](https://stackoverflow.com/q/605845/12149471) – Andreas Wenzel Dec 03 '22 at 23:32

1 Answers1

0

The function calloc initializes all the allocated memory to zero.

If you want to initialize all bytes of the memory to a different value, you can use malloc followed by memset.

However, in this case, you don't want to initialize all bytes to a same value, so you can't use memset.

Therefore, it would probably be best to use a loop:

//attempt to allocate memory
myArray = malloc( 102875 * sizeof(int) );
if ( myArray == NULL )
{
    fprintf( stderr, "Memory allocation error!\n" );
    exit( EXIT_FAILURE );
}

//initialize the memory
for ( size_t i = 0; i < 102875; i++ )
{
    myArray[i] = 0xFF;
}
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39