简体   繁体   English

为什么两个声明的char *变量获得相同的地址?

[英]Why are two declared char* variables getting the same address?

TL;DR: Why do my char* variables have the same value, even though I input different ones? TL; DR:为什么我的char *变量具有相同的值,即使我输入了不同的值?

Consider this very short program: 考虑这个非常短的计划:

char *GetCompleteString ()
{
    char *completeString;
    std::cout << "Please enter the complete string.\n";
    std::cin.getline(completeString,100);
    return completeString;
}

char *GetSubstring ()
{
    char* substring;
    std::cout << "Please enter the substring for which to search.\n";
    std::cin.getline(substring,100);
    return substring;
}


//////////////////////////////////////////////////
int main(int argc, const char * argv[])
{
    char *complete, *sub;

    complete = GetCompleteString();
    sub = GetSubstring();
    //diagnostic
    std::cout << "Complete is " << complete << " and sub is " << sub;
    //diagnostic

    return 0;
}

Now, I enter "foo" for the first string, and "bar" for the second. 现在,我为第一个字符串输入“foo”,为第二个字符串输入“bar”。 But the output tells me that both variables are the same. 但输出告诉我两个变量是相同的。

The Xcode debugger shows that both variables have the same address, so when I assign a value to bar, the previously-entered foo (which lives at the same address) takes the same value. Xcode调试器显示两个变量具有相同的地址,因此当我为bar分配值时,先前输入的foo(它位于同一地址)采用相同的值。 Here's what the debugger pane is showing just before the program exits: 以下是调试器窗格在程序退出之前显示的内容:

argv      const char **   0x00007fff5fbff928
argc      int             1
complete  char *          0x00007fff5fbff928
*complete char            'b'
sub       char *          0x00007fff5fbff928
*sub      char            'b'
&complete char **         0x00007fff5fbff8e8
&sub      char **         0x00007fff5fbff8e0

Why are these two variables being assigned the same address? 为什么这两个变量被赋予相同的地址? What am I missing here? 我在这里错过了什么? (And why are they retaining the same address as argv, which I think is just for interfacing with the CLI?) (为什么他们保留与argv相同的地址,我认为这只是为了与CLI连接?)

And are they even retaining the same addresses? 他们甚至保留了相同的地址吗? (I added the last two (&) lines to the debugger, myself. And those show different addresses...) (我自己在调试器中添加了最后两行(&)。那些显示不同的地址...)

What you are doing there is undefined behaviour since neither completeString nor substring point to actual allocated memory. 你在做什么是未定义的行为,因为completeStringsubstring都没有指向实际分配的内存。 Anything can happen ;) 任何事情都可能发生;)

To be more precise: It is very likely that since you don't assign a value to the local variables they just get the first value lying on the stack which could be random or something the initialisation of your libc left there. 更确切地说:很可能由于你没有为局部变量赋值,它们只是得到堆栈上的第一个值,这个值可能是随机的,或者你的libc的初始化就在那里。

You can use following updated code 您可以使用以下更新的代码

char *GetCompleteString ()
{
    char *completeString = (char*)malloc(sizeof(char)*numberofchars);
    std::cout << "Please enter the complete string.\n";
    std::cin.getline(completeString,100);
    return completeString;
}

char *GetSubstring ()
{
    char* substring =  (char*)malloc(sizeof(char)*numberofchars);
    std::cout << "Please enter the substring for which to search.\n";
    std::cin.getline(substring,100);
    return substring;
}


//////////////////////////////////////////////////
int main(int argc, const char * argv[])
{
    char *complete, *sub;

    complete = GetCompleteString();
    sub = GetSubstring();
    //diagnostic
    std::cout << "Complete is " << complete << " and sub is " << sub;
    //diagnostic

    return 0;
}

I have added memory allocation calls in your functions. 我在你的函数中添加了内存分配调用。 numberofchars is numbers of chars you expect in that char *, or you can give some more thought to make it dynamic numberofchars是你期望在char *中使用的字符数,或者你可以多考虑​​一下使它变得动态

There are a few problems with your code. 您的代码存在一些问题。 I will list them here - 我会在这里列出 -

  1. The statement char *completeString; 语句char *completeString; defines completeString to be a pointer to a character. completeString定义为指向字符的指针。 What you need is a character array to store the string entered by the user. 您需要的是一个字符数组,用于存储用户输入的字符串。

  2. The variable completeString and subString are local to the functions GetCompleteString and GetSubstring respectively. 变量completeStringsubString分别是函数GetCompleteStringGetSubstring本地变量。 They are allocated on the stack and go out of scope when the function returns. 它们在堆栈上分配,并在函数返回时超出范围。 If you try to access them in main , then this invokes undefined behaviour. 如果您尝试在main访问它们,则会调用未定义的行为。 You need to allocate space to store strings on the heap using new operator. 您需要使用new运算符分配空间来在堆上存储字符串。 This allocates memory on the heap. 这会在堆上分配内存。 You should free this memory using the delete[] operator after you are done with it. 完成后,应使用delete[]运算符释放此内存。

  3. The signature of main as per the standard should be one of the following - int main(); 根据标准的main签名应该是以下之一 - int main(); or int main(int argc, char *argv[]); int main(int argc, char *argv[]);

Applying these changes to your code, it is 将这些更改应用于您的代码,它是

#include <iostream>

#define MAX_LEN 100  

char *GetCompleteString()
{
    char *completeString = new char[MAX_LEN];
    std::cout << "Please enter the complete string.\n";
    std::cin.getline(completeString, MAX_LEN);
    return completeString;
}

char *GetSubstring()
{
    char* substring = new char[MAX_LEN];
    std::cout << "Please enter the substring for which to search.\n";
    std::cin.getline(substring, MAX_LEN);
    return substring;
}

int main()
{
    char *complete, *sub;

    complete = GetCompleteString();
    sub = GetSubstring();

    std::cout << "Complete is " << complete << " and sub is " << sub;

    delete[] sub;
    delete[] complete;

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么这两个整数变量和两个双精度变量(表面上)共享内存中的同一地址? - Why do these two integer variables and two double variables (seemingly) share the same address in memory? 即使使用malloc,两个char *是否可以具有相同的内存地址? - can two char * have the same memory address even with malloc? 为什么两个函数具有相同的地址? - Why do two functions have the same address? char * - 为什么指针中没有地址? - char* - why is there no address in the pointer? char *和char []无法获得相同的输出 - char* and char[] not getting same output 在同一地址上具有 2 个 std::atomic 变量的两个不同进程? - Two Different Processes With 2 std::atomic Variables on Same Address? 如何声明已经在类中声明的char变量的Char数组? - How to declare the Char array of char variables already declared in class? 为什么这两个局部变量的地址是一样的? - Why are the addresses of these two local variables the same? 为什么代码块中的cpp将相同的地址分配给函数中声明的变量,即使它多次调用? - Why cpp in code blocks assign same address to variable declared in a function even if it called many times? 为什么不显示char数据的地址? - Why is address of char data not displayed?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM