Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid type argument of unary '*' (have 'int') Error in C

Tags:

c

#include <stdio.h>
#include <stdlib.h>

/*
 * 
 */
int main() {

    int a[] = {5, 15, 34, 54, 14, 2, 52, 72};
    int p = &a[1];
    int q = &a[5]; 

    printf(*(p+3));
    printf(*(q-3));
    printf(*(q-p));
    printf(*p<*q);

    return (EXIT_SUCCESS);
}

Errors: "initialization makes integer from pointer without a cast [-Wint-conversion]" and "invalid type argument of unary '*' (have 'int')". First error is shown twice for the initialisation of variables above. Second error is shown for each print statement.

I'm not sure what is going wrong, anyone know how I can fix this?

like image 627
Imdad Avatar asked Mar 18 '17 14:03

Imdad


3 Answers

You forgot to make p and q int pointers. Also, you forgot to use the format specifier in the printf statements. Try the following:

#include <stdio.h>
#include <stdlib.h>

/*
* 
*/
int main() {
  int a[] = {5, 15, 34, 54, 14, 2, 52, 72};
  int *p = &a[1];
  int *q = &a[5];   

  printf("%d\n", *(p+3));
  printf("%d\n", *(q-3));
  printf("%d\n", *q-*p);
  printf("%d\n", *p<*q);
  return (EXIT_SUCCESS);
}
like image 162
VHS Avatar answered Nov 08 '22 08:11

VHS


&a[3] (or &a[5]) is a pointer type, i.e. int *.

p is defined as int.

So you need to define p and q as int *, like this:

int * p = &a[1];
int * q = &a[5];
like image 44
Mark Segal Avatar answered Nov 08 '22 06:11

Mark Segal


The unary operator & yields the address of its operand. The type is of T *, not T. Therefore you cannot assign a int * to an int without a cast. The expression

&a[1]

yields the address of a[1].

I think you mean to define the variables as pointers to int, not just ints.

int *p = &a[1];
int *q = &a[5]; 
like image 22
Edward Karak Avatar answered Nov 08 '22 07:11

Edward Karak