【问题标题】:Pointer issue when using with functions in c++在 C++ 中使用函数时的指针问题
【发布时间】:2021-12-05 00:37:17
【问题描述】:

我的程序有问题。

当我启动程序时,控制台没有显示它应该显示的 2 个数字,而是只显示:

Process returned -1073741819 (0xC0000005)   execution time : 1.759 s

这是我的代码:

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


Test(int* Ptr)
{
    Ptr=(int*)malloc(8);

    if(Ptr==0)
    {
        printf("malloc error\n");
    }

    Ptr[0]=155;
    Ptr[1]=800;
}

int main()
{
    int* m_Ptr=0;

    Test(m_Ptr);

    printf("%d  %d",m_Ptr[0],m_Ptr[1];

    return 0;
}

【问题讨论】:

  • 您是否尝试过调试程序?您将m_Ptr 按值传递给Test,因此打印取消引用原始空指针。
  • 试试这个:Test(int*&amp; Ptr)
  • 它甚至无法编译。您在第二个printf 末尾缺少),在return 语句中缺少;。这是你实际编译的吗?它是program,美式拼写...
  • 这看起来像 C,而不是 C++。你确定你知道你的程序应该使用哪种语言吗?

标签: c function pointers arguments


【解决方案1】:

您的主要问题是您传递给 test() 的指针是通过副本传递的。所以m_ptr 在传入时为空,在测试返回时仍为空。

你可能想稍微改变你的功能,更像:

int* Test()
{
    int * Ptr = (int*) malloc(20);

    if(Ptr==0)
    {
        printf("malloc error\n");
    }

    Ptr[0]=155;
    Ptr[1]=800;

    return Ptr; // Return the pointer by value
}

并使用like(主要):

int* m_Ptr = Test(m_Ptr);
// Now m_Ptr actually points to something...

【讨论】:

    【解决方案2】:

    test 中的参数Ptrmain 中的m_Ptr 是不同的内存对象 - 对test::Ptr 的任何更改(例如将malloc 的结果分配给它)都不会反映在@ 中987654327@。您必须将指针或对m_Ptr 的引用传递给test,或者test 必须返回分配给m_Ptr 的指针值:

    m_Ptr = Test(); // returns pointer to newly allocated memory.
    

    如果这是 C++,那么不要使用malloc(或calloc,或realloc)。要么使用vectorset 之类的标准容器(随着新项目的添加而自动增长),或者使用new 运算符手动为某种智能指针分配内存。 不要在 C++ 代码中使用 C 风格的内存管理;它是劳动密集型的,不安全的,而且很容易出错。

    【讨论】:

      【解决方案3】:

      使用malloc(8),您请求 8 个字节。 在 64 位系统上,sizeof(int) 可能是 8 个字节。 如果是这样,Ptr[1]=800; 行实际上会写入分配的 Arena 之外的内存。

      尝试将malloc行改为

      Ptr=(int*)malloc(sizeof(int)*2)

      【讨论】:

      • 非常感谢你们。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多