Dolly2929
Dolly2929

Reputation: 301

Array not correctly initialised using a pointer

I'm trying to create an array using a pointer and malloc() function, then initialising it through a for loop, however not all the values are initialised and some seem to be treated in a different way which I don't understand. In the first version I had written the for loop without the cast, which led to a warning: comparison between signed and unsigned integer expressions when compiling with -Wall -Wextra, and gave the same result anyway at the execution.

#include <stdio.h>
#include <stdlib.h>
#define N 50
#define SIZE sizeof(int)

void afficher (int *p) /* just to display the values of the array*/
{
    int i;
    for (i=0; i<=(int) ((N-1)*SIZE); i+=SIZE)
    {
        printf("%d ", *(p+i));
    }
    printf("\n\n");
}

int main()
{
    int * pointer = NULL;
    int i;
    pointer = malloc (N*SIZE);

    afficher(pointer); /*first display before initialising*/

    if (pointer)
    {
        for (i=0; i<=(int)((N-1)*SIZE); i+=SIZE) 
        {
            *(pointer+i) = 1; /*trying to initialise all values to 1 */
        }
    }

    afficher(pointer); /*second display*/
    free(pointer);
    return 0;
}

So, while I'm expecting the first display to show whatever was in memory before the program starts, I'd like all the values to be 1 at the second display, however what I'm getting is

0 0 0 0 0 0 0 0 0 0 0 0 0 540024880 540024880 540031032 825438256 8246 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

1 1 1 1 1 1 1 1 1 1 1 1 1 540090417 540090417 540487988 926430256 8246 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Even though the first display is a bit weird, I don't think it should cause an issue when I try to change the values and I have no idea why these values in the middle won't be changed to 1 like the others.

Upvotes: 0

Views: 50

Answers (1)

bolov
bolov

Reputation: 75707

You can't access uninitialized objects. malloc doesn't initialize the values of the allocated array so you can't print them. Doing so results in Undefined Behaviour.

Secondly, you have N elements so you need

for (i = 0; i < N; ++i)

The reason why you need N * sizeof(int) in malloc and N when traversing the array is that malloc is data type agnostic and deals with bytes of memory, but the variable pointer has data type int * so it knows that its elements are int

Upvotes: 1

Related Questions