简体   繁体   English

C ++ cout指针

[英]C++ cout pointer

Hello Can somebody explain why second cout in func(char *p) doesn't work: 您好有人可以解释FUNC(字符* P)为什么第二COUT不工作:

#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

using namespace std;

char *strhex(char *str);
char *func(char *p);

int  main()
{
     char *ptr;    

     char *p=strhex("d");
     cout<<"main:"<<p<<endl;

     cout<<func(p)<<endl;

     system("PAUSE");
     return 0;
}

char *func(char *p)
{ 
      cout<<"func1:"<<p<<endl;
      char buffer[500]="";
   char *zbuffer = buffer; 
      cout<<"func2:"<<p<<endl; ///doesn't work

      return zbuffer;
}

char *strhex(char *str)
{
     char buffer[500]="";
  char *pbuffer = buffer;
  int len = strlen( str );

     for( int i = 0; i < len ;i++ )
  {
  itoa(str[i],pbuffer,16);  
        pbuffer +=2;
     };

     *pbuffer = '\0'; 
     pbuffer=buffer;

     return pbuffer;
}

Edit: i'm using DEV C++ 4.9.9.2 on Windows 编辑:我在Windows上使用DEV C ++ 4.9.9.2

One big problem here is that strhex is returning a pointer to a local variable ( buffer[] ). 这里的一个大问题是strhex正在返回一个指向局部变量( buffer[] )的指针。 This variable goes out of scope at the end of the function, so the return value points at undefined memory contents that can be overwritten at any time. 该变量在函数末尾超出范围,因此返回值指向未定义的存储器内容,该内容可以随时覆盖。

Your entire code doesn't work. 您的整个代码无效。 Both functions return pointers to local arrays, which don't point to anything valid after the function returns. 这两个函数都返回指向本地数组的指针,该指针在函数返回后不会指向任何有效的东西。 That causes undefined behavior. 这会导致不确定的行为。 Since the value of p is one of these invalid pointers, you can't depend on it to be anything at any particular time — that memory probably gets overwritten during func() . 由于p的值是这些无效指针之一,因此您不能在任何特定时间将其视为任何值-内存可能在func()期间被覆盖。 You need to either new[] and delete[] the appropriate memory or, preferably, use a proper C++ data structure like std::string . 您需要new[]delete[]适当的内存,或者最好使用适当的C ++数据结构,例如std::string

看起来好像正在工作,但是main中的第二个cout没有打印出值,因为您正在返回一个空缓冲区。

Adding to others answers: 添加到其他答案:

You need not reset pbuffer to point to the start of the array and then return it's value: 您无需重置pbuffer即可指向数组的开头,然后返回其值:

pbuffer=buffer;
return pbuffer;

you can just say 你可以说

return buffer;

the array name is also a pointer(pointer to the first element of the array. 数组名称也是一个指针(指向数组第一个元素的指针。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM