0

I've been trying to return an array in C. I'm mostly acquainted with Java (where it's comparatively easier to return an array).

This is what I'm trying to do right now:

#include <stdio.h>
#include <stdlib.h>

int * duplicates(int[],int);

int main() {
    int arr[] = {3,5,6,5,9,5,10,11,3};
    int n = sizeof(arr)/sizeof(arr[0]);

    int * tempArray = duplicates(arr,n);

    for (int i = 0; i < n; i++) {
        printf("%d \t",tempArray[i]);
    }

}

int * duplicates(int arr[], int n) {
    int tempArray[n];
    int r = 0;
    int flag = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i+1; j < n; j++) {
            if (arr[i] == arr[j]) {
                for(int k = 0; k < r; k++) {
                    if(arr[i] == tempArray[k]) {
                        flag = 1;
                    }
                }
                if (flag == 0) {
                    tempArray[r++] = arr[i];
                    flag = 0;
                } else {
                    break;
                }

            }
        }
    }

    return tempArray;

}

And this, to no surprise - crashes my program. How I can return an array in C, because that feels like a bare-minimum, something I should know before I can move further into the language.

James Z
  • 12,209
  • 10
  • 24
  • 44
VenoM
  • 453
  • 3
  • 9
  • 17

2 Answers2

2

Yeah, just allocate the memory like here Returning an array using C

int * duplicates(int arr[], int n) {
    int *tempArray;
    ...
    tempArray = (int *)malloc(sizeof(int) * n);
    if (tempArray == NULL)
        return (NULL);
    ...

This will work. Google why you should 'dynamically allocate the memory' and 'pointer'.

  • 4
    [Do not cast the result of `malloc()`.](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Andrew Henle Jun 12 '21 at 12:22
  • 1
    Also, it is preferable to avoid `sizeof(type)`. So `malloc(n * sizeof *tempArray)` would be preferable here. It makes it clearer what the memory is used for, and since `sizeof` is not a function, the braces can be omitted by putting `n` in front. – Cheatah Jun 12 '21 at 15:27
0

the array you created inside function duplicate has automatic storage duration since it's on the stack of function unlike in java in which arrays are objects and allocated on the heap. anyway I just wanted to add some NOTE which is don't use VLA(variable length arrays) like int array[n] instead use literals like int array[50] since VLA generate a lot of assembly code(affect performance a tiny bit) and can have security problems like stack overflows or cause the program to crash. Also, not all compilers implement it(portability issues).

KMG
  • 1,433
  • 1
  • 8
  • 19