0

I have been trying to pass my array address to print array values in main function. But it is not working as it gives "Count by X.exe has stopped working". It also shows a warning message which says "function is returning address of local variables". I am not able to find the problems. It would be helpful if anyone finds pointer related problem of my code which is given below.

#include<stdio.h>

int * countBy(int x, int n)
{
    int arr[n];
    int count = x;

    for(int i = 0; i < n; i++)
    {
        arr[i] = count;
        count = count + x;
    }

    return arr;
}

int main()
{
    int x = 2, n = 10;
    int * prr;

    prr = countBy(x, n);

    for(int i = 0; i < 10; i++)
    {
        printf("%d ", prr[i]);
    }

    return 0;
}
klutt
  • 30,332
  • 17
  • 55
  • 95
Anim
  • 49
  • 6
  • This is close to a duplicate of [Pointer to local variable](https://stackoverflow.com/questions/4570366/pointer-to-local-variable). – Jonathan Leffler Sep 14 '19 at 16:53
  • Possible duplicate of [How to access a local variable from a different function using pointers?](https://stackoverflow.com/questions/4570366/how-to-access-a-local-variable-from-a-different-function-using-pointers) – S.S. Anne Sep 15 '19 at 03:39

2 Answers2

2

You cannot return arrays in C. You would either need to create the array in the main function and pass it to the function or use dynamic allocation.

Passing an output array:

void countBy(int x, int n, int *arr)
{
    int count = x;

    for(int i = 0; i < n; i++) {
        arr[i] = count;
        count = count + x;
    }
}

int main(void)
{
    int x = 2, n = 10;
    int arr[n];
    countBy(x, n, arr);
}

Dynamic allocation:

int * countBy(int x, int n)
{
    int *arr = malloc(n * sizeof(*arr));
    int count = x;

    for(int i = 0; i < n; i++) {
        arr[i] = count;
        count = count + x;
    }
    return arr;
}

int main(void)
{
    int x = 2, n = 10;
    int *prr;
    prr = countBy(x, n);
    free(prr); // Remember to use free to not cause memory leaks
}
klutt
  • 30,332
  • 17
  • 55
  • 95
  • I thought without using dynamic memory allocation it would be possible to pass array which seems not possible via c programming language. Thanks for your answer and explanation. – Anim Sep 14 '19 at 16:58
1

The local variables have a lifetime which extends only inside the block in which it is defined. The moment the control goes outside the block in which the local variable is defined, the storage for the variable is no more allocated (not guaranteed). Therefore, using the memory address of the variable outside the lifetime area of the variable will be undefined behaviour.

On the other hand you can do the following, replace the int arr[n] with a static array but the size of the array must be declared.

...
static int arr[10];
...

This will fix the problem but you couldnt change the size of the array if the user inputs the wanted size of it.