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?
![]()
asked Mar 28, 2011 at 7:30
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;
}
![]()
answered Mar 28, 2011 at 7:41
codaddictcodaddict
440k80 gold badges490 silver badges526 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 LeschinskiEric Leschinski
142k95 gold badges407 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 MundaSandro Munda
39.3k24 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 HeffernanDavid Heffernan
596k42 gold badges1053 silver badges1470 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
93k30 gold badges188 silver badges239 bronze badges
asked Dec 18, 2013 at 11:27
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
![]()
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
ChinnaChinna
3,8804 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. Показов 3632. Ответов 1 Метки нет (Все метки)
Необходимо отсортировать одномерный массив. Написал функцию, но компилятор выдаёт ошибку в строке 55: error: invalid type argument of unary ‘*’ (have ‘int’)
Что я сделал не так?
__________________
0 |
Вопрос:
Я работаю над c-программой, и вот структура, которую я использую
struct EngineParts{
int serial_number;
unsigned int year_of_manufacture;
unsigned int quantity;
char *material;
}*Eparts;
И я получаю следующую ошибку
`Automobile.c:79:5: error: invalid type argument of unary ‘*’ (have ‘unsigned int’)`
`Automobile.c:80:5: error: invalid type argument of unary ‘*’ (have ‘int’)`
`Automobile.c:81:5: error: invalid type argument of unary ‘*’ (have ‘unsigned int’)`
в этих трех строках
*new->quantity = quantity;
*new->serial_number = serial_number;
*new->year_of_manufacture = year_of_manufacture;
Вот полная реализация
void automobile_add_part(const int serial_number,
const unsigned int year_of_manufacture,
const unsigned int quantity ,
const char *material){
/*
* Store the address to the latest part
*/
struct EngineParts *new ;
new = (Eparts+available_number_of_parts);
// Copying a String is a little bit complicated
// First memory is allocated for the string
*new->material = (char *)calloc(strlen(material),sizeof(char));
//Then the string is copied
strcpy((char *)*new->material,material);
*new->quantity = quantity;
*new->serial_number = serial_number;
*new->year_of_manufacture = year_of_manufacture;
available_number_of_parts++;
}
PS:
Я проверил следующие вопросы:
error: недопустимый аргумент типа ‘унарный * (есть’ int)
Недопустимый аргумент типа → C structs
но они, похоже, не помогают мне.
Любые предложения по решению проблемы?
Лучший ответ:
Сделайте это так:
new->quantity = quantity;
Дополнительная разметка указателя (*new->quantity) является ошибкой: new->quantity – это int, а не какой-либо указатель, поэтому компилятор жалуется.
Разыменование указателя new (возможно ли законно иметь переменную с именем такой?) уже выполняется через operator->.
Ответ №1
Оператор -> уже разыскивает указатель для вас.
new->serial_number эквивалентен (*new).serial_number, оба из которых выглядят так, как вы хотите.
Ответ №2
Оператор -> разыскивает указатель, поэтому использование дополнительного * не требуется. И приводит к ошибке.
Ответ №3
нет необходимости * для new->quantity
-> является ярлыком для (*new).quantity
я пытаюсь использовать вектор с указателем и модулями.
У меня есть эта проблема с 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
Другие решения
Других решений пока нет …
Hey guys,
So as I stated in the title I am trying to make a mortgage calculator in C++, however I ran into the error that I stated in the title when trying to compile it. I’m quite new to C++ so there may be a blatantly obvious error somewhere and probably a lot of malpractice, so excuse me. Here is the code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Initialise variables
int hPrice; //Stores value of home price, as given by user
int dPay; //Same thing, except stores down payment
int term; //Same thing, except stores loan term
float interest; //Same thing, except stores annual interest rate
int nPrice; //Stores value of new price after down payment is taken away
int tMonths; //Stores value of term converted to months
float iDecimal; //Stores value of interest rate as a decimal
float cInterest; //Stores value of compound interest
float total; //Stores total monthly payment
//Get user input for hPrice, dPay, term and interest
cout << "Please enter the price of the home: ";
cin >> hPrice;
cout << "Please enter the down payment amount: ";
cin >> dPay;
cout << "Please enter the loan term in years: ";
cin >> term;
cout << "Please enter the annual interest rate as a percentage: ";
cin >> interest;
//Do necessary calculations to get values of nPrice, tMonths and cInterest
nPrice = hPrice - dPay;
iDecimal = interest / 100;
tMonths = term * 12;
cInterest = (nPrice * ((1 + (iDecimal / 1)) ** (1 * term))) - nPrice;
//Output monthly payment
cout << "The monthly payment will be £" << setprecision(2) << fixed << total;
}
When compiling, I get this error:
invalid type argument of unary ‘*’ (have ‘int’)
cInterest = (nPrice * ((1 + (iDecimal / 1)) ** (1 * term))) - nPrice;
I have no idea what this error means and googling resulted in things that weren’t relevant to what I was doing.
Thanks in advance for any ideas 🙂
This is my first question on here and im still learning c, and i was writing this code to enter details of a user bank account to file and reading all records back from file, when the error,
error:invalid type argument of unary ‘*» (have ‘int’) appeared on all lines that had pointer to struct *ptr pointed to integer values (eg line 40)
struct usr_act
{
char username[24], address[24], status;
int id, prebal, cp, newbal, pdate;
}a[3];
int j=0;
struct usr_act *ptr;
bool r;
void input()
{
FILE *fp;
fp = fopen("accounts.txt","a+");
if(fp==NULL)
{
printf("Error!!");
exit(1);
}
printf("ntRecord %dnn",j+1);
fprintf(fp,"Record",j+1);
printf("nName:- ");
for(int i=0;i<24;i++)
{
scanf("%c",ptr->username[i]);
}
fprintf(fp,"Name:- %s",*(ptr->username));
printf("nAddress:- ");
for(int i=0;i<24;i++)
{
scanf("%c",ptr->address[i]);
}
fprintf(fp,"Address:- %s",*(ptr->address));
printf("nCustomer Id:- ");
scanf("%d",ptr->id);
fprintf(fp,"Customer Id:- %d",*(ptr->id)); //Error
printf("nPrevious balance:- ");
scanf("%d",ptr->prebal);
fprintf(fp,"Previous Balance:- %d",*(ptr->prebal)); //Error
printf("nCurrent Payment:- ");
scanf("%d",ptr->cp);
fprintf(fp,"Current Payment:- %d",*(ptr->cp)); //Error
printf("nPayment Date:- ");
scanf("%d",ptr->pdate);
fprintf(fp,"Payment Date:- %d",*(ptr->pdate)); //Error
fclose(fp);
r=true;
}
void calc()
{
FILE *fp;
fp = fopen("accounts.txt","a+");
if(fp==NULL)
{
printf("Error!!");
exit(1);
}
float k;
k = 0.10 * (*(ptr->prebal));
if(*(ptr->cp)>0 && *(ptr->cp)<k)
{
ptr->status='o';
}
else
{
ptr->status='c';
}
fprintf(fp,"Account status:- %c",*(ptr->status));
ptr->newbal= *(ptr->prebal) - (*(ptr->cp));
fprintf(fp,"New Balance:- %d",*(ptr->cp));
fclose(fp);
}
and in between i have a display function which displays data from file and this is the main function
int main()
{
int l;
do
{
ptr=&a[j];
r=false;
printf("ntMenunk=1, Input details nk=2, Show patient records nk=3, Exit nnEnter your choice:- ");
scanf("%d",&l);
switch(l)
{
case 1:
{
input();
calc();
break;
}
case 2:
{
display();
break;
}
}
if(r==true)
{
j=j+1;
}
} while(l!=3);
return 0;
}
How can i solve this?
#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);
}