c - Adding multiple values to array -
i needed array hold 4 values defined within function fn1, created array: int somearray[4]; in main() . although understand values might entered array individually number: somearray[1]=3;, numbers in variables n1, n2, n3, n4.
is there method accomplish this?
i have considered possibility of creating array within function, transferring individual values somearray[].
i'm evidently quite new c, , thought of returning array came mind. i'm quite sure it's not right, have 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.. @ least that's attempting anyway
you can like:
char somearray[] = {n1, n2, n3, n4}; if write auxiliary function, allocate array on stack (i.e., put array in local variable), can't return it. because it's on stack, , overwritten in future. example, wouldn't say:
int *f() { unsigned a[] = {n1, n2, n3, n4}; } instead, use malloc, allocates memory on heap. so, contrast, can say,
int *f() { unsigned *a = malloc(sizeof(int)*4); ... return a; }
Comments
Post a Comment