gpt4 book ai didi

c++ - 如何避免-fpermissive?

转载 作者:太空宇宙 更新时间:2023-11-04 16:12:06 26 4
gpt4 key购买 nike

我写了下面的代码示例,我不得不使用 -fpermissive 来跳过错误/警告

#include <iostream>
#include <vector>
using namespace std;

int endOfProgram(){
printf("\n\npress return key to close the program...");
char end[2];
fgets(end, 2, stdin);
return 0;
}

void pointerTest(vector<int> * pointer){
printf("%d\n", pointer);
printf("%#x\n", (unsigned)pointer);
for (auto it = (*pointer).begin(); it < (*pointer).end(); it++)
printf("%d ", *it);
}

int main(){
vector<int> numbers = { 1, 2, 3, 4, 5, 6 };
pointerTest(&numbers);
endOfProgram();
}

错误/警告信息:

@test:~/workspace $ make
g++ -std=c++11 pointerTest.cc -o pointerTest -fpermissive
pointerTest.cc: In function ‘void pointerTest(std::vector<int>*)’:
pointerTest.cc:13:24: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘std::vector<int>*’ [-Wformat=]
printf("%d\n", pointer);
^
pointerTest.cc:14:28: warning: cast from ‘std::vector<int>*’ to ‘unsigned int’ loses precision [-fpermissive]
printf("%#x\n", (unsigned)pointer);
^

显然这两行是有问题的...

printf("%d\n", pointer);
printf("%#x\n", (unsigned)pointer);

问题:我该如何编写这些行,以避免使用 -fpermissive?

最佳答案

  1. 不要使用%d 打印指针。这是未定义的行为。
  2. 使用 %p 格式说明符打印出指针,而不是尝试将其转换为整数。

关于c++ - 如何避免-fpermissive?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27475467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com