如何在c++中为数组使用malloc和memset

How to use malloc and memset for array in c++?

本文关键字:malloc memset 数组 c++      更新时间:2023-10-16

我想声明一个存储在指针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是必需的吗?

谢谢!

快速答案:

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有一篇关于的好文章

编辑

我必须警告您,在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;

NO。您不需要malloc将数组声明为指针,因为数组本身就是指针。使用malloc与否的区别在于,当使用malloc时,数组是在堆中声明的,而不是在堆栈中声明的。

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

这是错误的:

int a[3]; a= {1,2,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));

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

int *A = new int[length];