【发布时间】:2021-03-18 21:43:37
【问题描述】:
以下代码是我的较大程序的简化版本,用于演示问题。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int m = 5;
char **words1;
char **words2;
void f(void *v) {
printf("v: %p\n", v);
int len = v==words1 ? 3 : 4;
printf("len: %d\n", len);
for (int i=0; i<m; i++) {
// What goes here?
/*
char *c = malloc(sizeof(char) * len);
c = (char*)v; // Something _like_ this?!
printf("%s\n", c);
*/
}
}
int main(int argc, char *argv[]) {
words1 = malloc(m * sizeof(char*));
printf("%p\n", words1);
words2 = malloc(m * sizeof(char*));
printf("%p\n", words2);
for (int i=0; i<m; i++) {
words1[i] = malloc(sizeof(char) * 3);
words2[i] = malloc(sizeof(char) * 4);
strcpy(words1[i], "22");
strcpy(words2[i], "333");
}
f(words1);
f(words2);
for (int i=0; i<m; i++) {
free(words1[i]);
free(words2[i]);
}
free(words1);
free(words2);
}
我有两个全局 **char 我认为在堆上(因为 malloc)。
f()的签名不能改变,即只能接受void *。
重要的是,在实际程序中,**char 中的数据对于堆栈来说太大了。
简而言之:如何从*void 取回**char?
【问题讨论】:
-
首先,为什么这些变量是全局变量?但专门针对您的问题,您可以分配它:
char **s = v; -
c = malloc(sizeof(char) * len); c = (char*)v;请注意,这没有意义,因此不清楚作为您想要做什么的示例。因为malloc某事然后立即在下一行覆盖/丢弃它是没有意义的。
标签: c void-pointers