Error indirection requires pointer operand int invalid

The purpose of this code is to pass a virtual address in decimal and output the page number and offset. After I compile my code using the gcc compiler on Linux I get this error: indirection re...

The purpose of this code is to pass a virtual address in decimal and output the page number and offset.

After I compile my code using the gcc compiler on Linux I get this error:

indirection requires pointer operand (‘int’ invalid)
virtualAddress = *atoi(argv[1]);

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <curses.h>

int main(int argc,char *argv[])

{

     unsigned long int virtualAddress,pageNumber,offset;

     if(argc<2){

          printf(" NO ARGUMNET IS PASSED");

          return 0;

     }

    virtualAddress = *atoi(argv[1]);

     //PRINT THE VIRTUAL ADDRESS

    printf("The Address %lu contains:",virtualAddress);

    //CALCULATE THE PAGENUMBER

    pageNumber = virtualAddress/4096;

     //PRINT THE PAGE NUMBER

    printf("n Page Number = %lu",pageNumber);

    //FIND THE OFFSET

    offset = virtualAddress%4096;

    //PRINTS THE OFFSET

    printf("n Offset = %lu",offset);

     getch();

    return 0;

}

Jabberwocky's user avatar

Jabberwocky

46.6k17 gold badges57 silver badges108 bronze badges

asked Jul 7, 2016 at 4:01

azizoh's user avatar

This error occurs when you want to create pointer to your variable by *my_var instead of &my_var.

answered Jul 11, 2019 at 9:03

Fusion's user avatar

FusionFusion

4,8085 gold badges40 silver badges47 bronze badges

virtualAddress = *atoi(argv[1]);

atoi function returns int (not int * so no need to dereference return value) and you try to dereference int , therefore , compiler gives an error.

As you need it in unsinged long int use strtoul

char * p;
virtualAddress = strtoul(argv[1], &p,10);

answered Jul 7, 2016 at 4:05

ameyCU's user avatar

ameyCUameyCU

16.4k2 gold badges25 silver badges40 bronze badges

2

Содержание

  1. Error indirection requires pointer operand
  2. компиляция — косвенное обращение требует операнда указателя и ожидаемых ошибок выражения
  3. Решение
  4. Другие решения
  5. Error indirection requires pointer operand
  6. компиляция — косвенное обращение требует операнда указателя и ожидаемых ошибок выражения
  7. Решение
  8. Другие решения
  9. Build fails: error: indirection requires pointer operand (‘void’ invalid), etc #401
  10. Comments

Error indirection requires pointer operand

I get this error when I try compiling my code is there a way I can fix this.

testings.cpp:69:48: error: indirection requires pointer operand
(‘List ::It’ invalid)
for (; begin != end; ++begin) this->Insert(*begin);
^

testings.cpp:114:12: note: in instantiation of function template specialization
‘List ::List
::It>’ requested here
List first (test.begin(), test.end());
^
testings.cpp:94:13: warning: expression result unused [-Wunused-value]
this->cur;

testings.cpp:69:26: note: in instantiation of member function
‘List ::It::operator++’ requested here
for (; begin != end; ++begin) this->Insert(*begin);
^
testings.cpp:114:12: note: in instantiation of function template specialization
‘List ::List
::It>’ requested here
List first (test.begin(), test.end());
^
1 warning and 1 error generated.

Don’t return a reference, just return It.

You haven’t defined operator!= for your iterators. (Although you might find that setting your end iterators internal pointer to «fin» is not going to work too well.)

Your Size method actually counts the nodes in the list, even though you have a size member that you could return (as long as you update it properly; for instance, RemoveFront should subtract 1 from it.).

Your default ctor has a pointless initializer_list in it.

In this function, the expression It(start) is a temporary object. The language refuses to take a (non-const lvalue) reference to it, because the referent would be destroyed immediately at the semicolon of the return statement.

You don’t want to return a reference to a temporary value at all: just return by value:

Same advice for end().

Then, your problem is that you never implemented operator overloads for List::It.
You also have never provided a suitable constructor for List::Node.

Источник

компиляция — косвенное обращение требует операнда указателя и ожидаемых ошибок выражения

Я продолжаю получать ошибки, подобные этим:

Решение

Не c++ эксперт, но я уверен, что для определения константы вам просто нужно использовать #define директива, за которой следует символ и значение, которое вы хотите присвоить ему (даже если само значение является выражением, даже если такое выражение ссылается на другую константу), фигурные скобки и конечная точка с запятой являются чрезмерными:

Составлено с первой попытки с такими исправлениями.

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

Причиной ошибки является точка с запятой в конце директивы #define.

Вы также использовали неправильный тип скобок, попробуйте вместо этого:

#define UNLEADED 3.45

#define SUPER (UNLEADED + 0.10)

#define PREMIUM (SUPER + 0.10)

Обратите внимание, что когда вы используете директиву #define, все, что следует за #define, подставляется в ваш код. В этом случае после запуска препроцессора ваш код выглядел так:

else if(gasType == «UNLEADED»)
<
cost = UNLEADED 3.45; * gallons;
>
else if(gasType == «SUPER»)
<
cost = ; * gallons;
>
else if(gasType == «PREMIUM»)
<
cost = PREMIUM ; * gallons;
>

Причина, по которой вы получили indirection requires pointer operand Ошибка была в том, что компилятор пытался интерпретировать это утверждение:

Поскольку * оператор имеет только один аргумент, он интерпретируется как разыменование указателя, к счастью для вас gallons переменная не является указателем типа. Если галлоны были объявлены типом указателя, т.е. double cost, *gallons; и cin если бы там не было, код скомпилировал бы, но не сделал бы то, что вы ожидаете, вероятно, бросив segfault.

Макросы, определенные с помощью #define, могут быть очень мощными и очень опасными. Обычно есть лучший способ добиться чего-то в c ++. В этом случае UNLEADED , SUPER_UNLEADED а также PREMIUM может быть объявлен как const double типа то есть

const double unleaded = 3.45;
const double super = unleaded + 0.10;
const double premium = super + 0.10;

Источник

Error indirection requires pointer operand

Hello guys,
i have a problem with Iterators. The exercise is to let the user input numbers in a vector. I then have to add the first and the last number, then the second and the second last number. etc. But in my for loop i get an error while i try to print the second iterator, whose job is to iterate through the vector from the back. The error message is:
Indirection requires pointer operand (‘long’ invalid)

Welcome to the forum.

It looks like the problem is in line 12, i.e., the math.

If «store.begin() = 0» and «store.end() = 10 then your formula would be » 0 + 10 — (0 / 2) or 0″ which would end up as «0 +10 — 0». Not quite the mid point you are looking for. I think what you want is: auto vectorMid = (store.begin() + (store.end()) — ((store.begin() + store.end())/2); . And yes due to the order of precedence, see http://www.cplusplus.com/doc/tutorial/operators/#precedence , All those () are necessary. Note look at level 5 and 6.

And I think I would move line 16 to line 13 and change the for loop to end with «it++, it2—)». Since the value of «store.end()» should not change and setting the value of «it2» inside would yield the same address each time.

Now I have not tested this yet. This is what I see for now. I will load it up and give it a try though.

Источник

компиляция — косвенное обращение требует операнда указателя и ожидаемых ошибок выражения

Я продолжаю получать ошибки, подобные этим:

Решение

Не c++ эксперт, но я уверен, что для определения константы вам просто нужно использовать #define директива, за которой следует символ и значение, которое вы хотите присвоить ему (даже если само значение является выражением, даже если такое выражение ссылается на другую константу), фигурные скобки и конечная точка с запятой являются чрезмерными:

Составлено с первой попытки с такими исправлениями.

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

Причиной ошибки является точка с запятой в конце директивы #define.

Вы также использовали неправильный тип скобок, попробуйте вместо этого:

#define UNLEADED 3.45

#define SUPER (UNLEADED + 0.10)

#define PREMIUM (SUPER + 0.10)

Обратите внимание, что когда вы используете директиву #define, все, что следует за #define, подставляется в ваш код. В этом случае после запуска препроцессора ваш код выглядел так:

else if(gasType == «UNLEADED»)
<
cost = UNLEADED 3.45; * gallons;
>
else if(gasType == «SUPER»)
<
cost = ; * gallons;
>
else if(gasType == «PREMIUM»)
<
cost = PREMIUM ; * gallons;
>

Причина, по которой вы получили indirection requires pointer operand Ошибка была в том, что компилятор пытался интерпретировать это утверждение:

Поскольку * оператор имеет только один аргумент, он интерпретируется как разыменование указателя, к счастью для вас gallons переменная не является указателем типа. Если галлоны были объявлены типом указателя, т.е. double cost, *gallons; и cin если бы там не было, код скомпилировал бы, но не сделал бы то, что вы ожидаете, вероятно, бросив segfault.

Макросы, определенные с помощью #define, могут быть очень мощными и очень опасными. Обычно есть лучший способ добиться чего-то в c ++. В этом случае UNLEADED , SUPER_UNLEADED а также PREMIUM может быть объявлен как const double типа то есть

const double unleaded = 3.45;
const double super = unleaded + 0.10;
const double premium = super + 0.10;

Источник

Build fails: error: indirection requires pointer operand (‘void’ invalid), etc #401

parser.tab.cpp:97:10: note: expanded from macro ‘YYLLOC_DEFAULT’ Current.filename(Rhs[1].filename());

^ parser.tab.cpp:5176:19: error: indirection requires pointer operand (‘void’ invalid) YYLLOC_DEFAULT (*yylsp, yyerror_range, 2);

parser.tab.cpp:97:3: note: expanded from macro ‘YYLLOC_DEFAULT’ Current.filename(Rhs[1].filename()); ^

parser.tab.cpp:5176:3: error: member reference type ‘MiniZinc::ParserLocation *’ is a pointer; did you mean to use ‘->’? YYLLOC_DEFAULT (*yylsp, yyerror_range, 2); ^

parser.tab.cpp:98:10: note: expanded from macro ‘YYLLOC_DEFAULT’ Current.first_line(Rhs[1].first_line());

^ parser.tab.cpp:5176:19: error: indirection requires pointer operand (‘void’ invalid) YYLLOC_DEFAULT (*yylsp, yyerror_range, 2);

parser.tab.cpp:98:3: note: expanded from macro ‘YYLLOC_DEFAULT’ Current.first_line(Rhs[1].first_line()); ^

parser.tab.cpp:5176:3: error: member reference type ‘MiniZinc::ParserLocation *’ is a pointer; did you mean to use ‘->’? YYLLOC_DEFAULT (*yylsp, yyerror_range, 2); ^

parser.tab.cpp:99:10: note: expanded from macro ‘YYLLOC_DEFAULT’ Current.first_column(Rhs[1].first_column());

^ parser.tab.cpp:5176:19: error: indirection requires pointer operand (‘void’ invalid) YYLLOC_DEFAULT (*yylsp, yyerror_range, 2);

parser.tab.cpp:99:3: note: expanded from macro ‘YYLLOC_DEFAULT’ Current.first_column(Rhs[1].first_column()); ^

parser.tab.cpp:5176:3: error: member reference type ‘MiniZinc::ParserLocation *’ is a pointer; did you mean to use ‘->’? YYLLOC_DEFAULT (*yylsp, yyerror_range, 2); ^

parser.tab.cpp:100:10: note: expanded from macro ‘YYLLOC_DEFAULT’ Current.last_line(Rhs[N].last_line());

^ parser.tab.cpp:5176:19: error: indirection requires pointer operand (‘void’ invalid) YYLLOC_DEFAULT (*yylsp, yyerror_range, 2);

parser.tab.cpp:100:3: note: expanded from macro ‘YYLLOC_DEFAULT’ Current.last_line(Rhs[N].last_line()); ^

parser.tab.cpp:5176:3: error: member reference type ‘MiniZinc::ParserLocation *’ is a pointer; did you mean to use ‘->’? YYLLOC_DEFAULT (*yylsp, yyerror_range, 2); ^

parser.tab.cpp:101:10: note: expanded from macro ‘YYLLOC_DEFAULT’ Current.last_column(Rhs[N].last_column());

^ parser.tab.cpp:5176:19: error: indirection requires pointer operand (‘void’ invalid) YYLLOC_DEFAULT (*yylsp, yyerror_range, 2);

parser.tab.cpp:101:3: note: expanded from macro ‘YYLLOC_DEFAULT’ Current.last_column(Rhs[N].last_column()); ^

10 errors generated.»>

FreeBSD 12.1
bison-3.6.4
clang-9

The text was updated successfully, but these errors were encountered:

Источник

Problem with Iterators

Hello guys,
i have a problem with Iterators. The exercise is to let the user input numbers in a vector. I then have to add the first and the last number, then the second and the second last number… etc. But in my for loop i get an error while i try to print the second iterator, whose job is to iterate through the vector from the back. The error message is:
Indirection requires pointer operand (‘long’ invalid)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  int main()
{
    
    int input;
    std::vector<int> store;
    
    while(std::cin >> input)
    {
        store.push_back(input);
    }
    
    auto vectorMid = store.begin() + (store.end() - store.begin())/2;
    
    for(auto it = store.begin(); it != vectorMid; it++)
    {
        auto it2 = store.end() - 1 - it;
        
        std::cout << *it2 << std::endl;
        //Error: Indirection requires pointer operand ('long' invalid)
    }
    
	return 0;
}

Your variable it2 isn’t an iterator. It’s a number (more accurately, a difference_type, but generally that’s a number). An iterator minus an iterator gives a number.

Ok, thank you very much!

Hello Vivty,

Welcome to the forum.

It looks like the problem is in line 12, i.e., the math.

If «store.begin() = 0» and «store.end() = 10 then your formula would be » 0 + 10 — (0 / 2) or 0″ which would end up as «0 +10 — 0». Not quite the mid point you are looking for. I think what you want is: auto vectorMid = (store.begin() + (store.end()) - ((store.begin() + store.end())/2);. And yes due to the order of precedence, see http://www.cplusplus.com/doc/tutorial/operators/#precedence , All those () are necessary. Note look at level 5 and 6.

And I think I would move line 16 to line 13 and change the for loop to end with «it++, it2—)». Since the value of «store.end()» should not change and setting the value of «it2» inside would yield the same address each time.

Now I have not tested this yet. This is what I see for now. I will load it up and give it a try though.

Hope that helps,

Andy

Hello Andy,
i fixed the problem, it2 wasn’t an iterator. I guess i got that error message because C++ thought I forgot to add the «pointer syntax» (The * and adress of operator) to it2.

1
2
3
4
5
6
7
8
9
int main()
{
    int q = 45;
    int p = q; //Missing "pointer syntax"

    std::cout << *p << std::endl;
    //Error:Indirection requires pointer operand ('int' invalid)
    return 0;
}

I did a program to see if my guess was right and i really got the same error message!
I now «fixed» the problem, i guess. I think it’s not the best way to do it but it works :)!
Here is the working code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{
    int input;
    std::vector<int> store;
    
    while(std::cin >> input)
    {        store.push_back(input);
    }
    
    auto vectorMid = store.begin() + (store.end() - store.begin())/2;
    
    for(auto it = store.begin(); it != vectorMid; it++)
    {
        auto difference = it - store.begin(); //Calculate position of the first Iterator
        auto it2 = store.end() - difference - 1; //Initialize second iterator (-1 because .end() is one off the end!)
        
        std::cout << *it + *it2 << std::endl;
    }
    
	return 0;
}

Thanks for your help guys :)!

Vivty

Hi Vivty,
I think there’s still more to do here. Firstly, it looks like an infinite while loop — you should control how many numbers you’re inputting, or parse a getline. Secondly, I entered «10 20 30» and got the output «40».

I then have to add the first and the last number, then the second and the second last number… etc

So… (10+30) + (20+20)? Should we get 80 instead?

Sample code with control over number of input integers (kept your latest below that):

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
#include <iostream>
#include <vector>

int main()
{
    int input;
    std::vector<int> store;
    
    int total;
    std::cout << "How many numbers would you like to enter? ";
    std::cin >> total;
    std::cout << "Please enter " << total << " space-separated numbers: ";
    for (int x=1; x<=total; ++x)
    {
        std::cin >> input;
        store.push_back(input);
    }
    std::cout << std::endl << std::endl;
    
    auto vectorMid = store.begin() + (store.end() - store.begin())/2;
    
    for(auto it = store.begin(); it != vectorMid; it++)
    {
        auto difference = it - store.begin(); //Calculate position of the first Iterator
        auto it2 = store.end() - difference - 1; //Initialize second iterator (-1 because .end() is one off the end!)
        
        std::cout << *it + *it2 << std::endl;
    }
    
	return 0;
}

Output:

How many numbers would you like to enter?  3
Please enter 3 space-separated numbers:  10 20 30


40

Last edited on

Hello icy1,
i don’t see any problem with the output. This program is intended to output the sum of the first and the last element, the second and the second last element etc. That means if you input an odd number like 3, you will only get one output, which is here: 40 (10 + 30). If i input 4 numbers:
50 20 80 30 i’ll get the output: 80 100
But you’re right, i should probably check if the number is odd and limit the numbers the user can input, thanks!
Next time i’ll try to make the explanation more detailed, im sorry if some of you misunderstood what i wrote.

Vivty

Last edited on

Ok, so you’re not summing the sums; just printing them out separately.
Even inputs are fine, but there’s a problem with odd inputs. First output should be «40» for sure, but the second one you should think about. Should it do 20+20 and output 40? or should it simply output 20? Basically, it’s completely ignoring the middle number.

Hope that helps ;D

Last edited on

For example, you could declare a forwards and a backwards iterator outside the loop and compare with <. After the loop is done, if they’re equal, then we had an odd number of elements and you can decide what you want to do (print value once, sum it, etc):

1
2
3
4
5
6
7
8
auto it = store.begin();
auto it2 = store.end() - 1;
for(; it<it2; ++it,--it2)
{
    std::cout << *it + *it2 << std::endl;
}
if (it == it2) // Odd number of elements
    std::cout << *it << std::endl;

Last edited on

Topic archived. No new replies allowed.

Here is a snippet of my code:

long long card = get_long_long();

long long *FindLength = *card;

long long *FindFirstTwoDigits = *card;

And here are the errors:

credit1.c:8:29: error: indirection requires pointer operand ('long long' 
invalid)
long long *FindLength = *card;
                        ^~~~~
credit1.c:10:37: error: indirection requires pointer operand ('long long' 
invalid)
long long *FindFirstTwoDigits = *card;

Could somebody help me with this?
Thanks in advance.

asked Aug 28, 2018 at 19:22

yuniFlaminjo's user avatar

What is supposed to be * card? We can not apply own operators of a pointer to a variable of integer type in this case. It seems that the compiler is interpreting this as an indirect operation of a pointer.
Well we have the statement:

long long * FindLength

this declares a pointer to an integer of type long long, a pointer can only contain a memory address, if what you want to do is assign the memory address of the card variable to FindLength you should do the following

long long * FindLength = &card;

I hope this answers your question, keep in mind that it is not very clear and I do not know exactly your intentions.

answered Aug 28, 2018 at 20:03

MARS's user avatar

MARSMARS

5,2013 gold badges12 silver badges23 bronze badges

1

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

Я продолжаю получать ошибки, подобные этим:

pitstop.cpp:36:23: error: indirection requires pointer operand

('double' invalid)

cost = UNLEADED * gallons;

^ ~~~~~~~

pitstop.cpp:40:14: error: expected expression

cost = SUPER * gallons;                               ^
#include <iostream>
#include <iomanip>
using namespace std;

#define UNLEADED 3.45;
#define SUPER {UNLEADED + 0.10};
#define PREMIUM {SUPER + 0.10};

/*
Author: Zach Stow
Date:
Homework
Objective:
*/

double cost, gallons;
string gasType, finish, stop;

int main()
{
for(;;)

{

cout <<"Hi, welcome to Pitstop.n";
cout <<"Enter the type of gas you need:";
cin >> gasType;
cout << endl;

cout <<"Enter the amount of gallons you need:";
cin >> gallons;
cout << endl;

if(gasType == "finish" || gasType == "stop")break;

else if(gasType == "UNLEADED")
{
cost = UNLEADED * gallons;
}
else if(gasType == "SUPER")
{
cost = SUPER * gallons;
}
else if(gasType == "PREMIUM")
{
cost = PREMIUM * gallons;
}

}
cout <<"You need to pay:$" << cost << endl;

return(0);

}

0

Решение

Не c++ эксперт, но я уверен, что для определения константы вам просто нужно использовать #define директива, за которой следует символ и значение, которое вы хотите присвоить ему (даже если само значение является выражением, даже если такое выражение ссылается на другую константу), фигурные скобки и конечная точка с запятой являются чрезмерными:

// [...]

#define UNLEADED 3.45
#define SUPER (UNLEADED + 0.10)
#define PREMIUM (SUPER + 0.10)

//[...]

Составлено с первой попытки с такими исправлениями.

3

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

Причиной ошибки является точка с запятой в конце директивы #define.

Вы также использовали неправильный тип скобок, попробуйте вместо этого:

#define UNLEADED 3.45

#define SUPER (UNLEADED + 0.10)

#define PREMIUM (SUPER + 0.10)

Обратите внимание, что когда вы используете директиву #define, все, что следует за #define, подставляется в ваш код. В этом случае после запуска препроцессора ваш код выглядел так:

else if(gasType == "UNLEADED")
{
cost = UNLEADED 3.45; * gallons;
}
else if(gasType == "SUPER")
{
cost = {UNLEADED + 0.10}; * gallons;
}
else if(gasType == "PREMIUM")
{
cost = PREMIUM {SUPER + 0.10}; * gallons;
}

Причина, по которой вы получили indirection requires pointer operand Ошибка была в том, что компилятор пытался интерпретировать это утверждение:

* gallons;

Поскольку * оператор имеет только один аргумент, он интерпретируется как разыменование указателя, к счастью для вас gallons переменная не является указателем типа. Если галлоны были объявлены типом указателя, т.е. double cost, *gallons; и cin если бы там не было, код скомпилировал бы, но не сделал бы то, что вы ожидаете, вероятно, бросив segfault.

Макросы, определенные с помощью #define, могут быть очень мощными и очень опасными. Обычно есть лучший способ добиться чего-то в c ++. В этом случае UNLEADED, SUPER_UNLEADED а также PREMIUM может быть объявлен как const double типа то есть

const double unleaded = 3.45;
const double super = unleaded + 0.10;
const double premium = super + 0.10;

1

Проблема: не могу вывести числа которые лежат в массиве. Думал, что в методе value нужно писать return *array[current], но получаю:

error: indirection requires pointer operand (‘int’ invalid)

Если убрать «разыменовыватель» return array[current] то я получаю мусор в выводе

1359699216
32767
0
0
1359699224
32767
1359699252
32767
1359699268
32767

Внутри конструктора я «для эксперимента» вписывал цикл, выводящий массив — выводит все очень хорошо. Но когда я пробую возвращать значение через функцию то получаю мусор.

Мне тяжко даются указатели и ссылки, все время путаюсь в них. Если не сложно, можете дать статейку где доступно все расписано?

Реализация:

  1. ArrayIterator.cpp

    #include <iostream>
    
    class ArrayIterator {
    private:
    
        int *array;
        int current;
        int size;
    
    public:
    
        ArrayIterator(int *array, int size) {
            this->size = size;
            this->current = 0;
        }
    
        void next() {
            if ( over() ) {
                return;
            }
            current += 1;
        }
    
        bool over() {
            int last = size - 1;
            return current > last;
        }
    
        int operator[](int index) {
            return array[index];
        }
    
        int value() {
            return array[current];
        }
    };
    
  2. main.cpp:

    #include "ArrayIterator.cpp"
    
    
    int main() {
        int array[10] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
        ArrayIterator seq(array, 10);
    
    
        for ( ; !seq.over(); seq.next() ) {
            std::cout << seq.value() << std::endl;
        }
    
        return 0;
    }
    

Ответы (2 шт):

В конструкторе класса вы забыли проинициализировать член класса array

ArrayIterator(int *array, int size) {
    this->size = size;
    this->current = 0;
}

Конструктор может выглядеть следующим образом

ArrayIterator( int *array, int size ) 
    : array( array ), current( 0 ), size( size )
{
}

Функции next и over могут быть написаны проще. Например

void next() 
{
    if ( !over() ) ++current;
}

bool over() const
{
    return !( current < size );
}

→ Ссылка

Автор решения: gbg

Простите, а поле array кто будет инициализировать, управдом?

Далее, полистайте Майерса. Разберитесь, что такое списки инициализации в конструкторе и зачем они нужны именно вам. Инициализировать поля так, как это делаете вы — неверно.

→ Ссылка

The Indirection requires pointer operand error message is shown on the screen when the programmer has created a pointer to a variable by using *my_var instead of &my_var.Fix the indirection requires pointer operand

This article will provide detailed knowledge of this error and ways to solve it. First, let’s start with the reasons that cause this issue and find the best solutions.

Contents

  • Why Does the Indirection Requires Pointer Operand Error Occur?
    • – Error in Syntax
    • – Cannot Take the Address of an Rvalue of Type ‘Byte’
    • – Using the Wrong Function
    • – Compiling Error
    • – Wrong Usage of the Buffer Function
    • – Dereferencing the Wrong Array Value
  • How To Resolve the Indirection Requires Pointer Operand Error?
    • – Correct the Syntax Errors
    • – Use Vector of Pointers C++ To Resolve the Error
    • – Solving (Cannot Take the Address of an Rvalue of Type ‘Byte’) Error
    • – Pass Pointer to Function C++: Compilation
  • Conclusion
  • Reference

The Indirection requires pointer operand error message occurs while programming because the compiler interpreted the indirect pointer operand. Some of the other reasons include syntax errors or compiling errors along with cannot take the address of an rvalue of type ‘byte’.

Other common reasons behind this situation involve:

  • Using the wrong function
  • Compiling error
  • Wrong usage of the Buffer function
  • Dereferencing the wrong array value

– Error in Syntax

Syntax errors are common while typing large programs. Syntax errors can include writing the wrong functions or using operations that create an undefined behavior. If the programmer is taking the address of a temporary object of type (any), and it is not defined, then during execution, an error will occur.Causes of indirection requires pointer operand

Moreover, if the programmer wants to create a pointer to their variable by using *my_var instead of &my_var, a syntax error will occur along with the pointer operand error message.

– Cannot Take the Address of an Rvalue of Type ‘Byte’

When the program cannot take the address of an rvalue of type ‘byte’, it shows a pointer error. It occurs when the conditional expression does not produce an lvalue. Following is an example for better understanding:

For Example:

fn main() {

a := ‘hello beautiful world’

for a := 1; a < a.len; a++ {

// bite := b[a]

str := tos3(b[a])

println(str)

}

}

– Using the Wrong Function

When a wrong function is used, just like a syntax error, it also shows an operand error in the program. In the below example, the atoi function returns an int, not int *.

Thus, there is no need to dereference the return value again. The compiler will show an error message if the programmer tries to dereference int. Here’s an example:

For example:

#include <stdio.h>

#include <stdint.h>

#include <stdlib.h>

#include <unistd.h>

#include <math.h>

#include <curses.h>

int main(int argc,char *argv[])

{

unsigned long int virtualAddress,pageNumber,offset;

if(argc<2){

printf(” NO ARGUMENT IS PASSED”);

return 0;

}

virtualAddress = *atoi(argv[1]);

//PRINT THE VIRTUAL ADDRESS

printf(“The Address of %lu contains:”,virtualAddress);

//CALCULATE THE PAGENUMBER

pageNumber = virtualAddress/4096;

//PRINT THE PAGE NUMBER

printf(“n The Page Number = %lu”,pageNumber);

//FIND THE OFFSET

offset = virtualAddress%4096;

//PRINTS THE OFFSET

printf(“n The Offset = %lu”,offset);

getch();

return 0;

}

The error in here is “virtualAddress = *atoi(argv[2]);”.

– Compiling Error

When the compiler interprets the program as an indirect operation of a pointer, it means the compiler is an incompatible pointer to integer conversion, and so, the error occurs during execution.More causes of indirection requires pointer operand

In other words, if the compiler and pointer are incompatible, a pointer error will occur. Let’s explain this using an example.

Program Example:

long long card = get_long_long();

long long *FindLength = *card;

long long *FindFirstTwoDigits = *card;

Explanation:

In this example, the programmer has used owned operators of a pointer to a variable of integer type. Thus, the compiler interprets this as an indirect operation of a pointer.

Moreover, the function (long long * FindLength) declares a pointer to an integer of type long long, but since a compiling error occurred, the program will instead show an error message.

– Wrong Usage of the Buffer Function

Understanding the buffer function is important because the wrong usage of it can cause errors such as pointer issues in the program. Some programmers confuse between buffer and &buffer[0].

The programmer should use the buffer as an argument instead of &buffer[0]. Passing an array has the same procedure as passing a pointer to its first element or passing pointers to functions.

In the example below, the programmer has used the wrong buffer function in their array. The &buffer[0] causes a pointer operand error message to occur.

For example:

if(!startJPGchecker(&buffer[0]))

bool startJPGchecker(BYTE *buffer)

{

if (*buffer[0] == 0xff && *buffer[1] == 0xd8 && *buffer[2] == 0xff && *buffer[3] >= 0xe0 && *buffer[3] <= 0xef)

{

return true;

}

else

{

return false;

}

}

– Dereferencing the Wrong Array Value

When the programmer uses arr[n] within the function, it gives them the nth value in that array instead of giving a pointer. Therefore, if the user is trying to dereference that value (*arr[n]), it will not work unless they use an array of pointers with it.

How To Resolve the Indirection Requires Pointer Operand Error?

To resolve the Indirection requires pointer operand error message, the programmer has to pass their pointers from the functions or use correct, defined, and direct pointers and commands. Furthermore, this error can be fixed by solving the cannot take the address of an Rvalue of a type byte error.

Let’s see all the possible reasons that can solve this error. They are explained below in detail.

– Correct the Syntax Errors

Using the correct functions will eliminate syntax errors and get rid of error messages related to pointers. There are various software that help in detecting these errors and help the user to correct them.Solutions for indirection requires pointer operand

Let’s take an example: the programmer is dereferencing a long program and needs it in an unsigned long int. Then instead of using “atoi” in “virtualAddress = *atoi(argv[1]);”, they should use the strtoul function. Here’s an example:

Program:

char * p;

virtualAddress = strtoul(argv[2], &p,11);

– Use Vector of Pointers C++ To Resolve the Error

When the programmer uses a vector of pointers c++ to resolve the error, they have to be careful with the pointers and operands. With the help of this function, the programmer can avoid pointer errors. Vector is used as an alternative to some pointers. Here’s an example;

For example:

#include <iostream>

#include <vector>

using namespace std;

int main()

{

char ch1 = ‘A’, ch2 = ‘B’, ch3 = ‘C’, ch4 = ‘D’, ch5 = ‘E’, ch6 = ‘F’;

vector vtr = {&ch3, &ch4, &ch3, &ch6, &ch7, &ch9};

for (int a=0; a<vtr.size(); a++)

cout << *vtr[a] << ‘ ‘;

cout << endl;

for (vector::iterator as = vtr.begin(); as != vtr.end(); as++)

cout << **as << ‘ ‘;

cout << endl;

return 0;

}

The output:

As you can see, the same list of alphabets is displayed twice. To elaborate, the first statement in the main() function creates six characters with their identifiers or pointers. Whereas the second statement represents these characters with their memory addresses, resulting in a vector of pointers to chars.

– Solving (Cannot Take the Address of an Rvalue of Type ‘Byte’) Error

When the rvalue of byte type is not addressed, the (cannot take the address of an rvalue of type ‘byte’) error message occurs. Due to this error, a pointer error also arises. Therefore, the programmer must use the correct commands to remove this error.

Let’s see the correct commands from the example above.

Program

fn main() {

a := ‘hello beautiful world’

for i := 0; i < a.len; i++ {

unsafe{

str := tos(a.str[i],1)

println(str)

}

}

}

– Pass Pointer to Function C++: Compilation

As mentioned above, the user cannot apply the owned operators of a pointer to a variable of integer type. If they do that, the compiler will show an error because it will interpret the program as an indirect pointer operation.More solutions for indirection requires pointer operand

Therefore, to remove this error, the programmer has to correct the syntax error and pass pointer to function C++. This means the pointer has to pass from the function for the compiler to interpret it correctly. However, this is suitable if the user is using C++ language. Let’s take an example.

Wrong program:

long long card = get_long_long();

long long *FindLength = *card;

long long *FindFirstTwoDigits = *card;

Correct program:

long long * FindLength = &card;

long long *FindLength = *card;

long long *FindFirstTwoDigits = *card;

Conclusion

After reading this article completely, the reader will have maximum knowledge about this error and they will be able to resolve it using the different methods shown in this article. Some important points to keep in mind are:

  • The pointer should define the operator. Otherwise, the error will occur.
  • No usage of pointers can cause the same error to occur.
  • While creating the pointers that will support the variables in the program, make sure to use the right functions.

The reader can now proceed to resolve similar programming errors by the guidance provided in this article. Thank you for reading!

Reference

  • https://cs50.stackexchange.com/questions/30016/pset1-error-indirection-requires-pointer-operand
  • https://stackoverflow.com/questions/38237355/error-indirection-requires-pointer-operand-int-invalid
  • https://www.reddit.com/r/cs50/comments/4c7gn4/passing_pointers_to_functions_error_indirection/
  • https://github.com/vlang/v/issues/3336
  • https://linuxhint.com/cpp-vector-pointers-examples/#2
  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

This topic has been deleted. Only users with topic management privileges can see it.

  • Hi Guys,

    I need Help.
    I’m getting the error «indirection requires pointer operand (» QTextStream «invalid).Why?
    Thanks

    void menupainel::on_btnConfirmar_clicked()
    {
        Pessoa *p=new Pessoa();
    
    
        QDate Mydate =ui->dateNasc->date();
        QString date = Mydate.toString();
    
        QString nome = ui->txtNome->text();
        QString idade = ui->txtIdade->text();
        QString sexo = ui->comboSexo->currentText();
        QString rg = ui->txtRG->text();
        QString email = ui->txtEmail->text();
        QString cidade = ui->txtCity->text();
        QString estado = ui->txtEstado->text();
        QString telefone = ui->txtTelefone->text();
        QString celular = ui->txtCel->text();
    
        p->setNome(nome.toStdString());
        p->setIdade(idade.toStdString());
        p->setSexo(sexo.toStdString());
        p->setRG(rg.toStdString());
        p->setData(date.toStdString());
        p->setEstado(estado.toStdString());
        p->setTelefone(telefone.toStdString());
        p->setCelular(celular.toStdString());
        p->setEmail(email.toStdString());
    
    
    
        QFile file("text.txt");
    
            if(!file.open(QIODevice::Append|QIODevice::Text))
                return;
    
            QTextStream out(&file);
            *out<<p->getNome()<<endl;
    
    
        using namespace std;
    
        ui->stackedWidget->setCurrentIndex(2);
    }
    
  • @Caio.Sousa said in Indirection requires pointer operand:

    *out<<p->getNome()<<endl;

    out is already an Object here, no need to dereference it again
    And it’s also not needed to create Pessoa on the heap here. You even forgot to delete it and created a memory leak.

  • So would it look like? I’m new to C ++ and QT

    • *out<<p->getNome()<<endl; becomes out<<p->getNome()<<endl;
    • remove using namespace std;
    • replace Pessoa *p=new Pessoa(); with auto p = std::make_unique<Pessoa>(); (requires #include <memory>)
  • @VRonin said in Indirection requires pointer operand:

    make_unique

    Ok, I’ll try, but removing the * out to out gave me a problem talking about the QString, when I put the QString variable it works normal

  • @Caio.Sousa
    Hi
    Are you using std::string ?

    QTextStream out(&file);
    out<<p->getNome()<<endl;

    QTextStream dont like std::string as far as i know
    and it seems p->getNome() returns a std::string ?
    Any reason why its not QStrings in Pessoa ?

  • @mrjj

    I did this:

    Dou um QString nome = ui->txtNome->text();
    p.setNome(nome.toStdString());

    there in the file I try to use the out<<p.getNome();

    Only then the error appears = «invalid operands to binary expression(‘QTextStream’ and ‘std::……..'»

  • Hi
    I was wondering if you need
    std::string ?
    If you change to QString, it will just work.

  • Понравилась статья? Поделить с друзьями:
  • Error incorrect rage multiplayer installation was detected to run correctly it needs to be installed
  • Error incorrect path to ini file что делать
  • Error incorrect packet size 58818 client
  • Error incorrect login dota pro circuit
  • Error incorrect data перевод