You are passing address of two int and one pointer(third argument), you should receive first two arguments in pointer(one *
) to int and third argument in pointer to pointer(two **
) of int:
void load(int* n, int* x, int **arr){
// ^ ^ one* ^ two **
*n = 10;
*x = 9;
}
In load function you can assign values to *n
and *x
because both points to valid memory addresses but you can't do **arr = 10
simply because arr
doesn't points to any memory (points to NULL) so first you have to first allocate memory for *arr
, do like:
void load(int* n, int* x, int **arr){
*n = 10;
*x = 9;
*arr = malloc(sizeof(int));
**arr = 10;
}
Is this documentation useful in C coding, and is it a good practice?
Yes
but Sometimes I documents my function arguments like in following ways:
void load(int n, // is a Foo
int x, // is a Bar
int **arr){ // do some thing
// something
}
A reference: for document practice
Edit As you are commenting, do like below I am writing, it will not give any error/because of malloc()
.
#include<stdio.h>
#include<stdlib.h>
void load(int* n, int* x, int **arr){
*n = 10;
*x = 9;
*arr = malloc(sizeof(int));
**arr = 10;
printf("\n Enter Three numbers: ");
scanf("%d%d%d",n,x,*arr);
}
int main(){
int n = 0, x = 0;
int *arr = NULL;
load(&n, &x, &arr);
printf("%d %d %d\n", n, x, *arr);
free(arr);
return EXIT_SUCCESS;
}
Compile and run like:
~$ gcc ss.c -Wall
:~$ ./a.out
Enter Three numbers: 12 13 -3
12 13 -3
As Commented by OP:
"Invalid convertion from void* to int*" when I change this to arr = malloc(sizeof(int)(*n));
syntax of malloc():
void *malloc(size_t size);
malloc() returns void*
and *arr
type is int*
that is the reason compiler messages because of different types : "Invalid convertion from void* to int*"
But I avoid casting when malloc(), since: Do I cast the result of malloc? (read Unwind's answer)