0

Hi im trying to use a function to initialize an array with random number. somehow i get this error that i couldnt be able to solve

void arrayInit(int *A, int n){
  int i;
  for ( i = 0; i < n; ++i)
  {
    A[i] = rand();
  } 
}

call arrayInit() in main

int main(void){

  int array1[1000];

  arrayInit(&array1, 1000);

    return 0;
}

I get error saying:

csort.c:62:13: warning: passing argument 1 of ‘arrayInit’ from incompatible pointer type
   arrayInit(&array1, 1000);
             ^
csort.c:8:6: note: expected ‘int *’ but argument is of type ‘int (*)[1000]’
 void arrayInit(int *A, int n){
      ^

4 Answers 4

3

You need the call for arrayInit to be like this:

arrayInit(array1, 1000);

Instead of this:

arrayInit(&array1, 1000);

The name of an array decays to be a pointer to the first element, which is what your function needs.

Sign up to request clarification or add additional context in comments.

1 Comment

You've fixed the bug, but array1 isn't a pointer to the first element, but instead decays to it. For example, sizeof(array1) isn't sizeof(int*).
1

When you have

int array1[1000];

The type of &array1 is int (*)[1000], which is not what arrayInit expects. By using

arrayInit(arra1, 1000);

you are letting compiler decay the array to a pointer, which of of type int* in your case.

An array does not decay to a pointer in couple of cases:

  1. When you use the & operator.
  2. When you use the sizeof operator.

Comments

0

The identifier of any array is a type * itself. So you need to call your function like this: arrayInit(array1, 1000);.

Calling your function with an address of a pointer(&array1) would require a int** A(a pointer to a pointer type) in your function definition, which is certainly not the thing to do in this case, since the indexing in this case would also give an error.

Comments

0

you can call arrayInit() using the '&' as:

arrayInit(&array1[0], 1000);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.