0

I needed an array to hold 4 values defined within a function fn1, so I created an array: int somearray[4]; in main() . Although I understand that values might be entered into an array individually by number: somearray[1]=3;, my numbers are in variables n1, n2, n3, n4.

Is there a method to accomplish this?

I have considered the possibility of creating an array within the function, then transferring individual values into somearray[].

I'm evidently quite new to C, and the thought of returning the array also came to mind. I'm quite sure it's not right, but it would help to have some confirmation anyway.

Thanks in advance.

To Makoto:

main(){
int sumarray[4];
int n1,n2,n3,n4;

int fn1(){
n1=1;
n2=23;
n3=29;
n4=14;

sumarray[]={n1,n2,n3,n4}

return 0;
}

return 0;
}

well.. at least that's what I was attempting to do anyway

1
  • Can you show some of your code? It's a bit unclear what your intention is. Commented Jun 5, 2012 at 23:37

2 Answers 2

1

You can do something like:

char somearray[] = {n1, n2, n3, n4};

If you write an auxiliary function, allocate the array on the stack (i.e., put the array in a local variable), then you can't return it. This is because it's on the stack, and will basically get overwritten in the future. For example, you wouldn't say:

int *f() { 
    unsigned a[] = {n1, n2, n3, n4};
}

Instead, you use malloc, which allocates memory on the heap. So, by contrast, you can say,

int *f() {
    unsigned *a = malloc(sizeof(int)*4);
    ...
    return a;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Okay the mistake was trying to define the array within the function when i could have defined the array outside after fn1 was run. Thanks guys.

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.