I have written a code for basic array creation and printing it's values in C. I would appreciate comments on how it can be improved, and the industry standards.
One issue I'm encountering is having no way to tell printArr() what the size of the array is.
Some questions-:
Can I use arr[i] anywhere in the functions instead of **arr? (Gave error when I tried it)
Can I usearr[i]anywhere in the functions instead of**arr? (Gave error when I tried it)What is the most common way of dealing with arrays when writing professional code? Is my approach correct?
int * initArr (int ** arr, int n) { *arr=(int ) malloc(sizeof(int)*n); printf("size is %d\n", sizeof(*arr)); int i; for (i=0;i<n;i++) { *(*arr+i)=i+10; } return *arr; }
void ** printArr (int ** arr, int n) { int i; for (i=0;i<n;i++) { printf("Arr element %d is %d\n", i, *(*arr+i)); } return *arr; }
int main(void) {
int *arr2; arr2=initArr(&arr2,10); printArr(&arr2,10); return 0;}
What is the most common way of dealing with arrays when writing professional code? Is my approach correct?
int * initArr (int ** arr, int n)
{
*arr=(int *) malloc(sizeof(int*)*n);
printf("size is %d\n", sizeof(*arr));
int i;
for (i=0;i<n;i++)
{
*(*arr+i)=i+10;
}
return *arr;
}
void ** printArr (int ** arr, int n)
{
int i;
for (i=0;i<n;i++)
{
printf("Arr element %d is %d\n", i, *(*arr+i));
}
return *arr;
}
int main(void) {
int *arr2;
arr2=initArr(&arr2,10);
printArr(&arr2,10);
return 0;
}
Running the above code (with includes for stdio and stdlib) produces:
size is 8
Arr element 0 is 10
Arr element 1 is 11
Arr element 2 is 12
Arr element 3 is 13
Arr element 4 is 14
Arr element 5 is 15
Arr element 6 is 16
Arr element 7 is 17
Arr element 8 is 18
Arr element 9 is 19