如何“重建”腐烂的**char?
以下代码是我的较大程序的简化版本,用于演示问题。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int m = 5;
char **words1;
char **words2;
void f(void *v) {
printf("v: %pn", v);
int len = v==words1 ? 3 : 4;
printf("len: %dn", len);
for (int i=0; i<m; i++) {
// What goes here?
/*
char *c = malloc(sizeof(char) * len);
c = (char*)v; // Something _like_ this?!
printf("%sn", c);
*/
}
}
int main(int argc, char *argv[]) {
words1 = malloc(m * sizeof(char*));
printf("%pn", words1);
words2 = malloc(m * sizeof(char*));
printf("%pn", 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中,堆栈中的数据太大了。
简而言之:我如何**char从*void?
回答
您可以简单地将其分配给正确的类型f():
char **f_words = v;
for (int i=0; i<m; i++) {
printf("%sn", f_words[i]);
}
此外,您识别单词长度的f()方式也不好。
您可以将长度作为附加参数传递给f(),也可以使用NULL指针终止单词列表。