Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

incompatible pointer type

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

like image 716
crea Avatar asked Feb 26 '23 22:02

crea


1 Answers

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)
like image 57
Greg Hewgill Avatar answered Mar 03 '23 16:03

Greg Hewgill