zoukankan      html  css  js  c++  java
  • C++一次指针问题和解决(char指针乱码)

    问题始末

    struct NameGroup
    {
        char* Name1;
        char* Name2;
    };
    
    NameGroup A()
    {
        NameGroup result;
    
        //From other dll get values to NameGroup.
        //result.Name1 = source.Value1 result.Name2 = souce.Value2
    
        return result;
    }
    //Question ↓
    void B()
    {
        NameGroup group = A();
        printf("Name1: %s", group.Name1);
        printf("Name2: %s", group.Name2);
    
        //Name1: !@#!@#
        //Name2: !@#!@#
    }

    主要是从其他地方读到字符串数据,传入结构体,然后传出。

    在C#里当然是没问题的,最近在用C++,这么用导致最后打出来的是乱码。

    后来发现,字符串是栈中,A函数执行结束就被销毁了,这时候结构里的指针就变成了野指针,所以就乱码了。

    解决:

    NameGroup A()
    {
        NameGroup result;
    
        //From Other dll get values to NameGroup.
        //result.Name1 = source.Value1 result.Name2 = souce.Value2
        //result.Name1 = strcpy(result.Name1, source.Value1);
        //result.Name2 = strcpy(result.Name2, source.Value2);
    
        return result;
    }

    最后在函数A里加了2行,把字符串拷贝出来得以解决。很多摸不着头脑的BUG,都是这个原因造成的

  • 相关阅读:
    MySQL的存储引擎
    MySQL的索引及执行计划
    MySQL的SQL基础应用
    MySQL基础入门
    代码质量检测SonarQube
    Jenkins持续集成
    Git版本控制及gitlab私有仓库
    jumpserver跳板机
    Keepalived高可用服务
    well-known file is not secure
  • 原文地址:https://www.cnblogs.com/hont/p/4198516.html
Copyright © 2011-2022 走看看