使用运算符[]访问一个函数中的字符串会影响C++中另一个函数的输出

access the string in one function with operator[] affects the output of the other function in C++

本文关键字:函数 字符串 影响 输出 另一个 C++ 一个 运算符 访问      更新时间:2023-10-16

编译上述函数时,它将不打印任何内容。而如果我们注释掉"char-tmp=num[0]",它将打印"===test==="

#include <iostream>
using namespace std;
void eval(string num)
{
    char tmp = num[0];
}
int main()
{
    int i;
    cout<<"===test==="<<endl;
    return 0;
}

我知道在执行过程中出现了问题。我在Cygwin中测试了它,使用以下g++版本:

$ g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-cygwin/5.2.0/lto-wrapper.exe
Target: x86_64-pc-cygwin
Configured with: /cygdrive/i/szsz/tmpp/gcc/gcc-5.2.0-1.x86_64/src/gcc-5.2.0/configure --srcdir=/cygdrive/i/szsz/tmpp/gcc/gcc-5.2.0-1.x86_64/src/gcc-5.2.0 --prefix=/usr --exec-prefix=/usr --localstatedir=/var --sysconfdir=/etc --docdir=/usr/share/doc/gcc --htmldir=/usr/share/doc/gcc/html -C --build=x86_64-pc-cygwin --host=x86_64-pc-cygwin --target=x86_64-pc-cygwin --without-libiconv-prefix --without-libintl-prefix --libexecdir=/usr/lib --enable-shared --enable-shared-libgcc --enable-static --enable-version-specific-runtime-libs --enable-bootstrap --enable-__cxa_atexit --with-dwarf2 --with-tune=generic --enable-languages=ada,c,c++,fortran,lto,objc,obj-c++ --enable-graphite --enable-threads=posix --enable-libatomic --enable-libgomp --disable-libitm --enable-libquadmath --enable-libquadmath-support --enable-libssp --enable-libada --enable-libgcj-sublibs --disable-java-awt --disable-symvers --with-ecj-jar=/usr/share/java/ecj.jar --with-gnu-ld --with-gnu-as --with-cloog-include=/usr/include/cloog-isl --without-libiconv-prefix --without-libintl-prefix --with-system-zlib --enable-linker-build-id
Thread model: posix
gcc version 5.2.0 (GCC)

但在我的Ubuntu 14.04中没有这样的问题。

有人能给我一个解释吗?真奇怪。谢谢

===更新:

为什么我这个问题得了-2分?

===更新2:===

问题解决了。我们必须安装5.2.0版本的所有相关组件(gcc-core、g++、libgcc、libsupc、libstdc++……)

这个问题是我以前见过的。你会发现你有一个关于入口点的警告。如果链接器无法确定,则默认将第一个函数作为入口点。此外,请注意,将main()移到第一个函数并不能解决问题,因为入口点是用不同的参数和不同的调用约定调用的。

我不确定你做错了什么,但如果你发布编译命令会有所帮助。

g++ -o test.exe test.cpp

是编译它的正确命令;注意,由于cygwin的原因,我们必须将其调用为./test(默认情况下,PATH中的当前目录是而不是)。