c - Trouble with using calloc with an array and returning a pointer -
as reference second part of assignment:
int* generatefibonacci(int size);
this function take input integer called size. value contained in size variable represent how many numbers in fibonacci sequence put array. function use
calloc
create array of size , fill arraysize
numbers fibonacci sequence, starting1
,1
. when array complete function return pointer it.
my trouble come in play when error in line 8 "warning: assignment makes , integer pointer without cast
". error in line 19 "warning: return makes pointer integer without cast
".
so question is, how suppose set calloc
make array size user, return pointer it?
#include <stdio.h> #include <stdlib.h> int* generatefibonacci(int size) { int i, array[size]; array[size]=(int*)calloc(size, sizeof(int)); array[0]=0; array[1]=1; for(i = 2; < size+1; i++) array[i] = array[i-2] + array[i-1]; return *array; } void printhistogram (int array[], int size) { int i, j; for(i=0; <= size; ++i) { for(j=0; j < array[i]; j++) { printf("*"); } printf("\n"); } } int main(void) { int array[100], size; printf("how big fibionacci number be? "); scanf("%i", &size); generatefibonacci(size); printhistogram(array, size); return 0; }
how suppose set calloc make array size user, return pointer it?
for 1d array of int * use printf()
, scanf()
int *array = {0}; size_t size = 0; printf("enter order of array"); scanf("%d", &size); array = malloc(size);//create memory space "size" elements if(array){//do other stuff}
but unclear example, , comment if intend using 2d array....
as stated in comments, have created int
array, attempted create memory it.
int i, array[size]; ... array[size]=(int*)calloc(size, sizeof(int));//wrong
as created, array
not need memory. memory created on stack automatic.
if wanted 2d array of int
. this:
int *array[size]; //create pointer int []
with this, can create array of arrays (in concept) in way:
for(i=0;i<size;i++) array[i]= calloc(size, sizeof(int));//do not cast output, not necessary
now, have size x size
2d array of int
. can assigned values in manner:
for(i=0;i<size;i++) for(j=0;j<size;j++) array[i][j]=i*j;//or more useful assignment
by way, adjust parameters of calloc()
statement needed, but note, casting output not necessary.
regarding return statement, function prototyped return int *
.
int* generatefibonacci(int size){...} //requires return of int *
if decide use 1d array, i.e. int *array={0}
(requiring allocate memory), return:
return array;//array `int *`, return it.
if using 2d array, return int *
, must decide of size
elements of array want return:
return array[i];//where `i` can index value, 0 size-1
Comments
Post a Comment