如何在c++中为数组使用malloc和memset
How to use malloc and memset for array in c++?
我想声明一个存储在指针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];
相关文章:
- 如果没有malloc,链表实现将失败
- malloc() 可能出现内存泄漏
- Cuda C++:设备上的Malloc类,并用来自主机的数据填充它
- C++中的memset函数工作不正常
- 当我尝试加载内核模块时,如何修复C++中的这个 malloc() 错误?
- 在C++中创建队列 - 什么是 malloc 错误?
- 如何在 malloc 内存中初始化非 POD 数据
- 使用 malloc() 时出现意外大小
- C++:在被本地字符串捕获后释放或销毁 malloc'd char *?
- 错误:malloc:对象 0x7f9edf504080 的 *** 错误:未分配正在释放的指针
- 将 malloc 替换为数组
- SIGSEGV on Boost UDP 套接字关闭 - tcache_get at malloc.c.
- Malloc 在使用线程并行化 SSH 调用时存在问题
- 如何将新更改为 malloc?
- 初始化数组、"memset"或" {//value} "的最佳方法是什么?
- 将 malloc 转换为新的正确方法
- Malloc void return char 数组有时不起作用(Terry Davis 对 C++);
- 如何通过 malloc 为队列数组分配内存?
- Malloc Memset就是这种用法
- 如何在c++中为数组使用malloc和memset