c++ - 将 char[] 转换为 char*

标签 c++ c

可能这是个棘手的问题,但请帮忙

void Temp1::caller()
{
char *cc=Called();  
printf("sdfasfasfas");
printf("%s",cc);
}

char *Temp1::Called()
{
char a[6]="Hello";
return &a;
} 

这里如何使用 printf("%s",cc); 打印 Hello

最佳答案

首先,这个函数:

char *Temp1::Called()
{
char a[6]="Hello";
return &a;
} 

正在返回一个局部变量,一旦函数结束,该变量将不复存在 - 更改为:

const char *Temp1::Called()
{
 return "Hello";
} 

然后,使用 printf() 打印字符串的方法是使用“%s”:

void Temp1::caller()
{
const char *cc=Called();  
printf("sdfasfasfas");
printf("%s",cc);
}

关于c++ - 将 char[] 转换为 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2666300/

相关文章:

c - Linux进程堆栈被局部变量溢出(堆栈保护)

c++ - 如何在 Linux 中创建可通过 Screen 应用程序连接的 pty

c++ - 用于创建文件名的预处理器指令

c++ - 哪个更好 : A unique_ptr to a 2D array or a 2D array of unique_ptrs?

c - C 中的 BST 链表 : Breadth First Search

c - 代码中的内存泄漏?

c++ - 测量大型方形网格中的簇有哪些好的替代方法?

c++ - 从守护进程中的 exec()'ed 进程读取 stdout/stderr

c++ - header 和未解析的外部符号

c++ - pthread_join 是一个瓶颈