【问题标题】:How to use malloc and memset for array in c++?如何在 C++ 中将 malloc 和 memset 用于数组?
【发布时间】:2014-04-20 19:53:27
【问题描述】:

我想声明一个存储在指针 A 中的数组。我有以下代码。

int length = 8;
int *A;
A = (int*) malloc(length*sizeof(int));
A = {5, 1, 3, 5, 5, 2, 9, 8};

但是,数组不能像上面那样初始化。错误显示“无法在赋值中转换为 'int'”。我该如何解决这个问题?

另外,在 c++ 中声明数组(用于指针)时是否需要 malloc 和 memset?

谢谢!

【问题讨论】:

  • 使用std::vector 会更好。 std::vector<int> A{5, 1, ..., 8};
  • @chris 您建议的实现 std::vector A{...} 似乎编译不正确。错误是“扩展初始化列表仅适用于.....”
  • 使用 -std=c++11 对吧?是的,它是 C++11 的一个特性。
  • 为什么在问题标记为 c++ 时使用 malloc ?你应该使用新的甚至更好的 std::vector

标签: c++ pointers malloc


【解决方案1】:

快速回答:

A[0] = 5;
A[1] = 1;
A[2] = 3;
A[3] = 5;
A[4] = 5;
A[5] = 2;
A[6] = 9;
A[7] = 8;

基本上,当您说“A =”时,您正在更改“A 指向的内容”。如果要更改“A 指向的值”,则必须使用[]*

cplusplus.com has a good article on that topic

编辑

我必须警告你,在 C++ 中使用 malloc 不是一个好习惯,因为它不会初始化也不会破坏复杂对象。

如果你有:

int length=8;
class C_A {
    C_A() {
        std::cout << "This cout is important" << std::endl;
    }
    ~C_A() {
        std::cout << "Freeing is very important also" << std::endl;
    }
};

C_A* A;
A = (C_A*) malloc(length*sizeof(C_A));
free(A);

你会注意到 cout 永远不会发生,而正确的是:

A = new C_A[length];
delete[] A;

【讨论】:

  • @return0 我编辑了我的答案,为什么 malloc 在 C++ 中可能不好,我建议你阅读它。
  • 非常感谢您的解释!
【解决方案2】:

没有。您不需要malloc 将数组声明为指针,因为数组本质上是指针。使用malloc或不使用的区别在于,使用malloc时,数组是在堆中声明的,而不是在栈中。

其次,当且仅当您在声明时填充数组时,您可以直接填充数组,例如 没错:int a[3]={1,2,3};

这是错误的:

int a[3]; a= {1,2,3};

【讨论】:

    【解决方案3】:

    使用 malloc() 和 memcpy() 做你想做的事的一种相当有效的方法是

    int initializer[] = {5, 1, 3, 5, 5, 2, 9, 8};
    int *A;
    A = (int*) malloc(length*sizeof(int));
    memcpy(A, initializer, length*sizeof(int));
    

    【讨论】:

      【解决方案4】:

      使用new代替malloc,返回T*而不是void*,支持异常:

      int *A = new int[length];
      

      【讨论】:

      • 在 C++ 中忘记 malloc()。对于 memset,可以使用 std::fill(A, A + sizeof(A), 0)。
      • @return0, malloc 仅适用于特定情况。我绝对会建议您至少在您了解原因之前远离。
      猜你喜欢
      • 1970-01-01
      • 2020-08-17
      • 2019-06-13
      • 2013-11-17
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多