当函数返回反向字符串的地址时,我无法打印元素 [英] I cannot print the element when the function return address for reverse string

查看:49
本文介绍了当函数返回反向字符串的地址时,我无法打印元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近正在编写一个函数来反转字符串输入.例如输入=hello",然后输出=olleh"我有一个问题,当我返回 char* 的地址时,它看起来不错,但是为什么我无法打印该指针的字符串?

I'm recently writing a function to reverse a string input. For example, input = "hello", then output = "olleh" I got a question, when I return the address of char*, it looks fine, but why I cannot print the string of that pointer ?

首先非常感谢,这是我的代码:

many thanks at first and here is my code :

#include <stdlib.h>
#include <stdio.h>

char* reverseString(char*);

int main(void)
{
    char* s = "hello";
    char* out;

    out = reverseString(s);

    printf("%p %s\n", out, out);
    return 0;
}

char* reverseString(char* s)
{
    int i;
    int size;
    char* reverse;

    size = sizeof(s);
    char reversechar[size];

    for (i = 1; i < size + 1; i++)
        reversechar[i - 1] = s[size - i];

    reverse = reversechar;
    //printf("%p\n",reverse);
    return reverse;
}

结果:0x7fff40db7300 @@

result : 0x7fff40db7300 @@

推荐答案

不要在函数内部分配reversechar.当函数返回时,它将超出范围(即不再有效访问它).而是在 main 中分配它并传递一个指向该函数的指针.类似的东西:

Don't allocate reversechar inside the function. It will go out of scope when the function returns (i.e. it is not valid to access it anymore). Instead allocate it in main and pass a pointer to the function. Something like:

 #include <stdio.h>
 #include <stdlib.h>

 void reverseString(char* dst, char* s)
 {
    int i;
    int size;

    size = strlen(s);

    for(i = 0; i < size; i++)
      dst[i] = s[size-1-i];

    // Terminate the string
    dst[size] = 0;

 }

 int main(void)
 {
    char* s = "hello";
    char out[strlen(s)+1];

    reverseString(out, s);

    printf("%p %s\n",out,out);

    return 0;
 }

将其与 strcpymemcpy 之类的函数进行比较.他们不会为你分配内存.它们要求您同时提供源指针和目标指针.

Compare this to functions like strcpy and memcpy. They don't allocate memory for you. They require you to give both the source and the destination pointer.

这篇关于当函数返回反向字符串的地址时,我无法打印元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆