Aisha
Aisha

Reputation: 13

How do I print the values being stored in the function, function returns a pointer

I'm very new to programming so please bear with me!

This is my code (in C):

int * arrayExpander(int arr[], int size);

int main()
{
    int arr[] = { 1,2,3,4,5 };
    int size = 5;
    int* arrPtr = arrayExpander(arr, size);

    for (int i = 0; i < size * 2; i++) {
        printf("New array: %d \n", *arrPtr);
    }
}

int * arrayExpander(int arr[], int size)
{
    int newInt[10];
    int* expandedArr = &newInt;

    //move elements from original to expanded and initialise remaining elements with 0

    for (int i = 0; i < size * 2; i++) {
        if (i < size) {
            expandedArr[i] = arr[i];
        } else {
            expandedArr[i] = 0;
        }
    }
    return expandedArr;
}

My print statement isn't printing the values stored in the expandedArr correctly. I've tried a few variations and not sure how to fix it.

Thanks in advance

Upvotes: 1

Views: 35

Answers (1)

Krishna Kanth Yenumula
Krishna Kanth Yenumula

Reputation: 2567

In your code, expandedArr is a local pointer variable, which gets destroyed, after we return from function. We need to allocate memory using malloc to extend their lifetime. See the below code :

#include<stdio.h>
#include<stdlib.h>
int * arrayExpander(int arr[], int size);

int main()
{
    int arr[] = { 1,2,3,4,5 };
    int size = 5;
    int* arrPtr = arrayExpander(arr, size);

    for (int i = 0; i < size * 2; i++) {
        printf("New array: %d \n", *(arrPtr+i)); // *arrPtr prints only first element
    }
}

int * arrayExpander(int arr[], int size)
{
    
    int* expandedArr = malloc(10*sizeof(int)); // You need allocate memory in heap

    //move elements from original to expanded and initialise remaining elements with 0

    for (int i = 0; i < size * 2; i++) {
        if (i < size) {
            expandedArr[i] = arr[i];
        } else {
            expandedArr[i] = 0;
        }
    }
    return expandedArr;
}

The output :

New array: 1 
New array: 2 
New array: 3 
New array: 4 
New array: 5 
New array: 0 
New array: 0 
New array: 0 
New array: 0 
New array: 0 

Upvotes: 1

Related Questions