I just started programming so pointers and arrays confuse me. This program just assigns random numbers from 0 - 9 into array and prints them out
(#include <stdio.h> #include <stdlib.h> #include <time.h>)
int function(int *num[]){
int i;
for(i=0; i<10; i++){
srand((unsigned)time(NULL));
*num[i] = rand()%10;
printf("%d", *num[i]);
}
return 0;
}
int main(){
int num[10];
function(&num); // incompatable pointer type (how do i fix this?)
return 0;
}
Thankyou
Change your code to read something like this:
int function(int num[]){
int i;
for(i=0; i<10; i++){
srand((unsigned)time(NULL));
num[i] = rand()%10;
printf("%d", num[i]);
}
return 0;
}
int main(){
int num[10];
function(num);
return 0;
}
In main()
, you are allocating an array of 10 integers. The call to function(num)
passes the address of this array (technically, the address of the first element of the array) to the function()
function. In a parameter declaration, int num[]
is almost exactly equivalent to int *num
(I'll let you ponder on that one). Finally, when you access the elements of num[]
from within the function, you don't need any extra *
. By using num[i]
, you are accessing the i
'th element of the array pointed to by num
.
It may help to remember that in C, the following are exactly the same:
num[i]
*(num+i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With