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.

2
  • 2
    Does this answer your question? Returning an array using C Commented Jun 12, 2021 at 11:59
  • Just nitpicking (I enjoy that): In java you can't return an array, only references to arrays. Commented Jun 12, 2021 at 14:35

2 Answers 2

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'.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.