下面的代码是指向"指针数组";密码我不确定这是否正确。
tags[0][0] = malloc(sizeof(char)*5);
strcpy(tags[0][0],"hi");
tags[0][1] = malloc(sizeof(char)*5);
strcpy(tags[0][1],"h2");
有人能告诉我以下代码中的上述行是否正确吗。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char *(*tags)[2] = malloc (2 * sizeof *tags);
tags[0][0] = malloc(sizeof(char)*5);
strcpy(tags[0][0],"hi");
tags[0][1] = malloc(sizeof(char)*5);
strcpy(tags[0][1],"h2");
tags[1][0] = "<head";
tags[1][1] = "</head>";
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
printf (" %s", tags[i][j]);
putchar ('n');
}
free (tags);
}
上面的和指针到指针的数组之间有什么区别吗?
这个
char *(*tags)[2]
意味着CCD_ 1是指向2个字符指针的数组的指针。
所以当你做时
char *(*tags)[2] = malloc (2 * sizeof *tags);
您可以分配一个由两个char指针组成的两个数组的数组。它相当于:
char* tags[2][2];
当而不是使用动态分配时。
所以是的,代码很好。这正是方法。当你想要一个动态的2D数组时,你应该总是这样做。
然而,您的代码缺少:
free(tags[0][0]);
free(tags[0][1]);
BTW:将指向动态分配内存的指针和指向字符串文字的指针存储在同一数组中是位"0";奇怪的";并且可能是有问题的,因为您需要跟踪哪些指针指向free
,哪些指针不释放。
这对我来说还可以。我在实践中很少看到这样的指针,但我会将tags
描述为";指向字符指针的2大小数组的指针";。当您malloc (2 * sizeof *tags);
时,您将为这些2大小的字符指针数组中的两个创建空间。这是你从每一行得到的:
char *(*tags)[2] = malloc (2 * sizeof *tags);
tags -----> [char*][char*] // index 0 of tags
[char*][char*] // index 1 of tags
// You now have 4 character pointers in contiguous memory that don't
// point to anything. tags points to index 0, tags+1 points to index 1.
// Each +1 on *(tags) advances the pointer 16 bytes on my machine (the size
// of two 8-byte pointers).
下一个malloc
:
tags[0][0] = malloc(sizeof(char)*5);
+-------> 5 bytes
|
tags ------> [char*][char*] // index 0
^
index 0 of tags[0], this now points to 5 bytes
第一次strcpy
之后
strcpy(tags[0][0],"hi");
+-------> {'h', 'i', ' ', <2 more> }
|
tags ------> [char*][char*] // index 0
下一个malloc
tags[0][1] = malloc(sizeof(char)*5);
+-------> 5 bytes
|
tags ------> [char*][char*] // index 0
^
index 1 of tags[0], this now points to 5 bytes
下一个strcpy
strcpy(tags[0][1],"h2");
+-------> {'h', '2', ' ', <2 more> }
|
tags ------> [char*][char*] // index 0
最后,字符串文字分配
tags[1][0] = "<head";
tags[1][1] = "</head>";
tags -----> [char*][char*] // index 0 of tags
[char*][char*] // index 1 of tags
| |
| |------> points to string literal "</head>"
|--------------> points to string literal "<head"
如果你真的想好好清理,你应该
free(tags[0][1]);
free(tags[0][0]);
// the order of the above doesn't really matter, I just get in the
// habit of cleaning up in the reverse order that I malloced in.
// But if you free(tags) first, you've created a memory leak, as
// there's now no existing pointers to tags[0][0] or [0][1].
free(tags);
当然,只要进程退出,操作系统就会回收所有内存。
您想要实现的是字符串数组。
char ***tags = malloc(sizeof(char**) * numberofpointers);
for (int i = 0; i < numberofpointers; ++i)
{
tags[i] = malloc(sizeof(char*) * numberofstringsperpointer);
}
for (int i = 0; i < numberofpointers; ++i)
{
for (int j = 0; j < numberofstringsperpointer; ++j)
{
tags[i][j] = malloc(sizeof(char) * (numberofcharacterperstring + 1));
}
}
strcpy(tags[0][0], string)