[英]C language: How to use memset to reset dynamic 2d array?
everyone! 大家!
I know that calloc
can allocate memory on heap for dynamic 2d array and initialize the memory to '\\0'. 我知道calloc
可以在堆上为动态2d数组分配内存,并将内存初始化为'\\ 0'。 However, after I have used the dynamic array, I want to reset it to zero again. 但是,在使用动态数组之后,我想再次将其重置为零。 The source code I wrote is below: 我写的源代码如下:
First of all, I defined macro as follow: 首先,我将宏定义如下:
#define MAX_NR_VERTICES 5000
#define MAX_NR_VERTICESdiv8 625
#define REPORTERROR(file_name, line_num, message) \
printf("[%s--%d] %s\n", file_name, line_num, message)
#define CALLOC(arg, type, num, file_name, line_num, message) \
if ((arg = (type *)calloc(num, sizeof(type))) == NULL) { \
REPORTERROR(file_name, line_num, message); \
exit(EXIT_FAILURE); \
}
#define FREE(arg) \
free(arg)
Then, I defined dynamic array and used it as follow: 然后,我定义了动态数组,并如下使用它:
...
char **graph = NULL;
CALLOC(graph, char *, MAX_NR_VERTICES, __FILE__, __LINE__, "cannot allocate memory for char **graph in _tmain function.\n");
for (int i = 0; i < MAX_NR_VERTICES; i++) {
CALLOC(graph[i], char, MAX_NR_VERTICESdiv8, __FILE__, __LINE__, "cannot allocate memory for char (*g) [] in _tmain function.\n");
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
graph[i][j] = 0x80;
printf("%d ", graph[i][j]);
}
printf("\n");
}
...
Everything was working well up to now. 到目前为止,一切都运转良好。 Then, I wanted to reset the dynamic 2d array to zero again: 然后,我想将动态2d数组再次重置为零:
memset(graph, 0, MAX_NR_VERTICES * MAX_NR_VERTICESdiv8 * sizeof(char));
The error occurred. 发生错误。 The error information was: 错误信息是:
Unhandled exception at 0x0FDA3FD4 (msvcr120d.dll) in 0xC0000005: Access violation writing location 0x0074F000.
What is the mistake in my program and how to use memset correctly here if I want to reset dynamic 2d array? 如果我想重置动态2d数组,程序中的错误是什么?如何在此处正确使用memset?
I use Visual Studio 2013 (C++) ultimate edition. 我使用Visual Studio 2013(C ++)终极版。
Thank you very much! 非常感谢你!
It appears that you've assumed that all the memory allocated for the elements of graph
are contiguous. 看来您已经假设为graph
元素分配的所有内存都是连续的。 That's not a valid assumption. 这不是一个有效的假设。 You'll need to reset the contents of each element of graph
separately: 您需要分别重置graph
的每个元素的内容:
for(i = 0 ; i < MAX_NR_VERTICES; i++)
memset(graph[i], 0, sizeof(char) * MAX_NR_VERTICESdiv8);
Best of luck. 祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.