redchicken
redchicken

Reputation: 319

Return malloc in C

int* dec2bin(int y){
    int *arr = (int*)malloc(sizeof(int)*5);
    int i;
    
    for (i=0; i<5; i++) arr[i]=0;
    
    return arr;
}

In this code, I write 0 to arr[0] through to arr[4], but the function returns 1070192. I want to return 00000.

What am I doing wrong?

Upvotes: 1

Views: 5630

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

The function returns pointer to the allocated memory

int* dec2bin(int y){
    int *arr = (int*)malloc(sizeof(int)*5);
    int i;

    for (i=0; i<5; i++) arr[i]=0;

    return arr;
}

for an array of 5 integers. Its address may not be equal to 0 unless the allocation failed. But the integers themselves are equal to 0.

If you will write the call for example the following way (it is not clear the meaning of the parameter)

int *p = dec2bin( 0 );

then *p, the first element of the array, will be indeed equal to 0

Or even you can write

int *p = dec2bin( 0 );

for ( int i = 0; i < 5; i++ ) printf( "%i ", p[i] );

and you will get that all elements of the array are equal to 0.

Upvotes: 1

frogatto
frogatto

Reputation: 29285

If you would like to get value of that array as a string (array of characters), below is the code you can start off by.

char* dec2bin(int y) {
    int *arr = (int *) malloc(sizeof(int) * 5);
    char output[50];
    int i;

    for (i=0; i<5; i++) arr[i] = 0;
    sprintf(output, "%d%d%d%d%d", arr[0], arr[1], arr[2], arr[3], arr[4]);

    return output;
}

For printing it out, you could use:

char *string = dec2bin(0);
printf("%s", string);

Upvotes: 0

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

Most probably you are printing the address returned by malloc().

You need a loop to print the contents, for example

int *dec2bin(int size)
{
    return calloc(size, sizeof(int));
}

int main(void)
{
    int *data;
    int  index; 
    int  size;

    size = 5;
    data = dec2bin(size);
    if (data == NULL)
        return -1; /* allocation error */
    for (index = 0 ; index < size ; index++)
        printf("%d", data[index]);
    printf("\n");
    free(data);

    return 0;
}

You can see that I used calloc(), that's because you are going to initialize all the values to 0, otherwise use malloc() instead.

Upvotes: 5

Related Questions