Error invalid type argument of unary have int

I have a C Program: #include int main(){ int b = 10; //assign the integer 10 to variable 'b' int *a; //declare a pointer to an integer 'a' a=(in...

I have a C Program:

#include <stdio.h>
int main(){
  int b = 10;             //assign the integer 10 to variable 'b'

  int *a;                 //declare a pointer to an integer 'a'

  a=(int *)&b;            //Get the memory location of variable 'b' cast it
                          //to an int pointer and assign it to pointer 'a'

  int *c;                 //declare a pointer to an integer 'c'

  c=(int *)&a;            //Get the memory location of variable 'a' which is
                          //a pointer to 'b'.  Cast that to an int pointer 
                          //and assign it to pointer 'c'.

  printf("%d",(**c));     //ERROR HAPPENS HERE.  

  return 0;
}    

Compiler produces an error:

error: invalid type argument of ‘unary *’ (have ‘int’)

Can someone explain what this error means?

Eric Leschinski's user avatar

asked Mar 28, 2011 at 7:30

picstand's user avatar

0

Since c is holding the address of an integer pointer, its type should be int**:

int **c;
c = &a;

The entire program becomes:

#include <stdio.h>                                                              
int main(){
    int b=10;
    int *a;
    a=&b;
    int **c;
    c=&a;
    printf("%d",(**c));   //successfully prints 10
    return 0;
}

Eric Leschinski's user avatar

answered Mar 28, 2011 at 7:41

codaddict's user avatar

codaddictcodaddict

440k80 gold badges490 silver badges527 bronze badges

1

Barebones C program to produce the above error:

#include <iostream>
using namespace std;
int main(){
    char *p;
    *p = 'c';

    cout << *p[0];  
    //error: invalid type argument of `unary *'
    //peeking too deeply into p, that's a paddlin.

    cout << **p;    
    //error: invalid type argument of `unary *'
    //peeking too deeply into p, you better believe that's a paddlin.
}

ELI5:

The master puts a shiny round stone inside a small box and gives it to a student. The master says: «Open the box and remove the stone». The student does so.

Then the master says: «Now open the stone and remove the stone». The student said: «I can’t open a stone».

The student was then enlightened.

answered Sep 30, 2013 at 19:18

Eric Leschinski's user avatar

Eric LeschinskiEric Leschinski

142k95 gold badges408 silver badges332 bronze badges

I have reformatted your code.

The error was situated in this line :

printf("%d", (**c));

To fix it, change to :

printf("%d", (*c));

The * retrieves the value from an address. The ** retrieves the value (an address in this case) of an other value from an address.

In addition, the () was optional.

#include <stdio.h>

int main(void)
{
    int b = 10; 
    int *a = NULL;
    int *c = NULL;

    a = &b;
    c = &a;

    printf("%d", *c);

    return 0;
} 

EDIT :

The line :

c = &a;

must be replaced by :

c = a;

It means that the value of the pointer ‘c’ equals the value of the pointer ‘a’. So, ‘c’ and ‘a’ points to the same address (‘b’). The output is :

10

EDIT 2:

If you want to use a double * :

#include <stdio.h>

int main(void)
{
    int b = 10; 
    int *a = NULL;
    int **c = NULL;

    a = &b;
    c = &a;

    printf("%d", **c);

    return 0;
} 

Output:

10

answered Mar 28, 2011 at 7:32

Sandro Munda's user avatar

Sandro MundaSandro Munda

39.4k24 gold badges98 silver badges121 bronze badges

4

Once you declare the type of a variable, you don’t need to cast it to that same type. So you can write a=&b;. Finally, you declared c incorrectly. Since you assign it to be the address of a, where a is a pointer to int, you must declare it to be a pointer to a pointer to int.

#include <stdio.h>
int main(void)
{
    int b=10;
    int *a=&b;
    int **c=&a;
    printf("%d", **c);
    return 0;
} 

answered Mar 28, 2011 at 7:44

David Heffernan's user avatar

David HeffernanDavid Heffernan

596k42 gold badges1055 silver badges1471 bronze badges

0

error: invalid type argument of unary ‘*’ (have ‘int’)

struct test_t {
    int var1[5];
    int var2[10];
    int var3[15];
}

test_t* test;
test->var1[0] = 5;

How can I solve this problem?

Maroun's user avatar

Maroun

93k30 gold badges188 silver badges239 bronze badges

asked Dec 18, 2013 at 11:27

Snidereng's user avatar

You should write:

struct test_t* test;

Or use typedef if you want to avoid writing struct every time you declare a variable of that type:

typedef struct test_t {
    int var1[5];
    int var2[10];
    int var3[15];
} test_t;

test_t* test;

Side note: In C++ the struct name is placed in the regular namespace, therefore there is no need to write struct before declaring a variable of that type.

answered Dec 18, 2013 at 11:27

Maroun's user avatar

MarounMaroun

93k30 gold badges188 silver badges239 bronze badges

When you declare a structure variable, struct keyword should be there like

struct test_t* test;

If you don’t want to use struct keyword every time you declare a variable, simply use typedef.

answered Dec 18, 2013 at 11:36

Chinna's user avatar

ChinnaChinna

3,8904 gold badges24 silver badges52 bronze badges

Написал код, вроде правильный,но вылезли ошибки от которых я не могу избавиться даже смотря ответы на зарубежных форумах. Вставил код целиком. Пишу в Atom компилирую через gcc
Вот что выдает компилятор:

spoiler

C:UsersFiretheestleYandexDiskТТИТLabs>gcc Kimlaba7.c -o Kimlaba7.exe
Kimlaba7.c: В функции :
Kimlaba7.c:20:23: ошибка: invalid type argument of unary <*> (have )
printf(«%2d n»,*(X+i*4+j));
^
Kimlaba7.c: В функции :
Kimlaba7.c:31:19: ошибка: invalid type argument of unary <*> (have )
int i=0,j=0,max=*(X+i*4+j),maxj=0;;
^
Kimlaba7.c:34:14: ошибка: invalid type argument of unary <*> (have )
if(max>*(X+i*4+j)){
^
Kimlaba7.c:35:13: ошибка: invalid type argument of unary <*> (have )
max=*(X+i*4+j);
^
Kimlaba7.c:39:5: ошибка: invalid type argument of unary <*> (have )
*(X+i*4+max)=0;
^
Kimlaba7.c: В функции :
Kimlaba7.c:45:8: предупреждение: при передаче аргумента 1 указатель преобразуется в целое без приведения типа
VVOD(A);
^
Kimlaba7.c:6:5: замечание: expected but argument is of type
int VVOD(int X){
^
Kimlaba7.c:46:9: предупреждение: при передаче аргумента 1 указатель преобразуется в целое без приведения типа
VIVOD(A);
^
Kimlaba7.c:15:5: замечание: expected but argument is of type
int VIVOD(int X){
^
Kimlaba7.c:47:15: предупреждение: при передаче аргумента 1 указатель преобразуется в целое без приведения типа
MAXANDOBMEN(A);
^
Kimlaba7.c:30:5: замечание: expected but argument is of type
int MAXANDOBMEN(int X){

Компилирую командой:
gcc Kimlaba7.c -o Kimlaba7.exe
А вот сам код:

/*
Дана матрица В(8,8). Заменить в каждой строке  матрицы
      максимальный элемент нулем.
*/
#include<stdio.h>
int VVOD(int X){
  int i,j;
  printf("Vvedite massive:n");
  for(i=0;i<4;i++){
    for(j=0;j<4;j++){
      scanf("%d",X+i*4+j );
    }
  }
}
int VIVOD(int X){
  int i,j,k=0;
  printf("Vivod massiva n");
  for(i=0;i<4;i++){
    for(j=0;j<4;j++){
      printf("%2d n",*(X+i*4+j));
      k++;
      if(k==4){
        printf("n");
        k=0;
      }

    }
  }
}
int MAXANDOBMEN(int X){
  int i=0,j=0,max=*(X+i*4+j),maxj=0;;
  for(i=0;i<4;i++){
    for(j=0;j<4;j++){
      if(max>*(X+i*4+j)){
        max=*(X+i*4+j);
        maxj=j;
      }
    }
    *(X+i*4+max)=0;
  }

}
int main(){
  int A[4][4];
  VVOD(A);
  VIVOD(A);
  MAXANDOBMEN(A);
}

Помогите пожалуйста разобраться ;з
ПРОБЛЕМА РЕШЕНА ВОТ РАБОЧИЙ КОД:

/*
Дана матрица В(8,8). Заменить в каждой строке  матрицы
      максимальный элемент нулем.
*/
#include<stdio.h>
int VVOD(int* X){
  int i,j;
  printf("Vvedite massive:n");
  for(i=0;i<4;i++){
    for(j=0;j<4;j++){
      scanf("%d", X+i*4+j );
    }
  }
}
int VIVOD(int* X){
  int i,j,k = 0;
  printf("Vivod massiva n");
  for(i=0; i < 4; i++){
    for(j=0; j < 4; j++){
      printf("%3d", *(X+i*4+j));
      k++;
      if(k == 4){
        printf("n");
        k = 0;
      }

    }
  }
}
int MAXANDOBMEN(int* X){
  int i = 0, j = 0, k = 0,max = 0, maxj = 0;
  for(i = 0; i < 4; i++){
    max = *(X+i*4+j);
    for(j = 0; j < 4; j++){
      if(max < *(X+i*4+j)){
        max = *(X+i*4+j);
        maxj = j;
      }
    }
    j=0;
    *(X+i*4+maxj) = 0;
}

}
int main(){
  int A[4][4];
  VVOD(*A);
  VIVOD(*A);
  MAXANDOBMEN(*A);
  VIVOD(*A);
}

i_sarapin

0 / 0 / 0

Регистрация: 28.03.2017

Сообщений: 18

1

Ошибка с указателями

30.03.2017, 17:05. Показов 3657. Ответов 1

Метки нет (Все метки)


Необходимо отсортировать одномерный массив. Написал функцию, но компилятор выдаёт ошибку в строке 55: error: invalid type argument of unary ‘*’ (have ‘int’)

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
void sortuj(int tab[], int N);
void swap(int*, int*);
 
int main(void)
{
    srand(time(NULL));
    int N1, N2;
    printf("Podaj rozmiar tablicy t1: ");
    scanf("%d", &N1);
    printf("nPodaj rozmiar tablicy t2: ");
    scanf("%d", &N2);
 
    int t1[N1];
    int t2[N2];
 
    for(int i = 0; i < N1; i++)
    {
        t1[i] = 1 + rand() % 10;
        printf("%d ", t1[i]);
    }
    printf("n");
    for(int i = 0; i < N2; i++)
    {
        t2[i] = 1 + rand() % 10;
        printf("%d ", t2[i]);
    }
    printf("n");
 
    sortuj(t1, N1);
    sortuj(t2, N2);
    printf("n");
 
    return 0;
}
 
void sortuj(int tab[], int N)
{
    for(int i = 1; i < N; i++)
    {
        for(int j = i; j > 0 && tab[j - 1] > tab[j]; j--)
        {
            swap(&tab[j - 1], &tab[j]);
        }
    }
}
 
void swap(int *x, int *y)
{
    int temp = *x;
    *x = *y;
    *y = *temp;
}

Что я сделал не так?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



#include <stdio.h>
int _area(), _vol(), (*fnptr)();// declare the functions and the function pointer here

_area(a,b)
int a, b;
{
    return (a*b); //The return value of _area after parameters are passed to it
}
_vol(fnptr,c) //engaging the function pointer as a parameter
int c;
{
    fnptr = _area(); //initializing the function pointer to function _area
    int k = (*fnptr)(8,9); // error occurs here
    return (k*c);
}

Compiling produces an error ,

:error: invalid type argument of ‘unary *’ (have ‘int’)


Using function prototypes I believe the code should look something like this:

#include <stdio.h>
int _area(int a, int b);

int _vol(int (*fnptr)(int, int), int);;// declare the functions and the function pointer here

int _area(int a, int b)
{
    return (a*b); //The return value of _area after parameters are passed to it
}

int _vol(int (*fnptr)(int, int),int c) //engaging the function pointer as a parameter
{
    fnptr = _area; //initializing the function pointer to function _area
    int k = fnptr(8,9); // error occurs here
    return (k*c);
}

я пытаюсь использовать вектор с указателем и модулями.
У меня есть эта проблема с C ++:
В main.cpp:

    #include<iostream>
using namespace std;
#include "Funcion1.hpp"
int main (int argc, char *argv[]) {
int vec[20];
int *punteroV = &vec[0];
for(int i = 0;i < 10;i++){
cout<<"Ingrese numero: ";
cin>>vec[i];
}
cout<<FUN(*punteroV) << endl;
return 0;
}

и в модуле:

#include "Funcion1.hpp"#include<iostream>
using namespace std;
int FUN(int &punteroV){

int num;
for(int i = 0;i<10;i++){
for(int j = 0;j<10;j++){
cout<<"i: "<<(punteroV+ i)<<endl<<"j: "<<(punteroV + j)<<endl;
if(*(punteroV + i) > *(punteroV + j)){
num = (punteroV + i);
}
}
}
return num;
}

и в модуле .hpp

   #ifndef FUNCION1_H
#define FUNCION1_H
int FUN(int&);
#endif

Компилятор выдает ошибку:

  error invalid type argument of unary '*' (have 'int')

Что означает эта ошибка?

-3

Решение

В функции FUN у вас есть эта строка:

   if(*(punteroV + i) > *(punteroV + j))

Вы пытаетесь сделать арифметику указателя на ссылку на целое число, а затем расценить его как int* Вы не можете сделать это прямо на ссылку. Чтобы сделать математику по ссылке, вы должны сначала взять ее адрес следующим образом:

   if(*(&punteroV + i) > *(&punteroV + j)){

0

Другие решения

Других решений пока нет …

Siddarth777

Expand|Select|Wrap|Line Numbers

  1. #include<stdio.h>
  2. main()
  3. {
  4. int *a=5;
  5. int **p=&a;
  6. fflush(stdin);
  7. printf(«%u,%u,%d»,p,*p,**p);
  8. }

getting compiled perfectly but am getting
«segmentation fault» in runtime
please help

Sep 18 ’10
#1

✓ answered by Siddarth777

thanks a lot for the reply
i have a doubt
in the above program in the statement
int *a=5
does that symbolizes implicitly that a value is holding the memory location of 5?
i dint understand what is invalid about that……as am a newbie in c programming pointers concept
please help

Banfa

Banfa

9,065
Expert Mod 8TB

The problem is that the pointer a does not point anywhere valid.

You say it compiles perfectly, do you get no compiler warnings? If not you probably don’t have you compiler warning level set high enough.

The reason I say this is that on line 4 you assign an int to an int *. This effectively makes a point at memory location 5, almost certainly not a valid location on your system.

p points to a

So when you try to print

p is valid, it is the address of a
*p is valid it is a, the address of an int
**p is not valid it is the thing that a points to, that is memory location 5, not the address of an allocate int and you get a segmentation fault (a memory address fault).

You can not take the address of a numerical constant like 5.

Sep 18 ’10
#2

Siddarth777

thanks a lot for the reply
i have a doubt
in the above program in the statement
int *a=5
does that symbolizes implicitly that a value is holding the memory location of 5?
i dint understand what is invalid about that……as am a newbie in c programming pointers concept
please help

Sep 18 ’10
#3

Banfa

Banfa

9,065
Expert Mod 8TB

int *a=5;

does explicitly set the value of a to (the memory location) 5. There is nothing wrong in that apart from being a little strange.

The problem comes when you try to dereference a with *a, you try to access the memory location contained in a, in this case 5 and that is not a valid memory location, or a least one you do not have access rights to.

Sep 18 ’10
#4

Your code has a point to whatever int is stored at address 0x0005. The segmentation fault occurs because the operating system has not granted your program permission to access this address. In addition, you might get a run-time alignment fault if your program runs on one of the many processors that don’t allow ints to be at odd addresses.

Do you intend for a to point to an int whose value is 5? If so, then you want something like this:

Expand|Select|Wrap|Line Numbers

  1. int five = 5;
  2. int *a = &five;

Sep 18 ’10
#5

Sign in to post your reply or Sign up for a free account.

Понравилась статья? Поделить с друзьями:
  • Error invalid transaction termination
  • Error invalid token error description token is incorrect перевод
  • Error invalid texture index 3ds max
  • Error invalid terms in product
  • Error invalid suffix x on integer constant