有人可以向我解释为什么我的输出中缺少第一个指针 (stringarray[0]) 以及如何解决它。我还想知道如何释放所有 malloc 指针的内存。
int main(int argc, char **argv) {
[...]
char ** stringarray;
if (( stringarray = (char **)malloc(counter*sizeof(char)))== NULL){exit(0);}
int k = 0;
for (i = 0; i < len; i =i+1){
if((strcmp(countries, districts[i]) == 0) && ( argvIntPeoplelimit <= people[i])) {
if (( stringarray[k] = (char * ) malloc(100*sizeof(char)))== NULL){exit(0);}
snprintf(stringarray[k],100,"The Country %s has %d people.",countries[i],people[i]);
printf("%d %d %s %s %d\n",i,k,stringarray[k], countires[i],people[i] ); //here stringarray[k] k==0 has a value
k=k+1;
}
}
write_file(stringarray,counter);
for (int f = 0; f < k; ++f)
{
// if i call stringarray[0] nothing shows up
//ERROR can't free(stringarray);
}
return 0;
}
我不知道如何用字符串构建结构指针,使我能够将数据处理到 write_file 函数的“char *result[]”。
void write_file(char *result[], int len);
非常感谢任何帮助、技巧和提示!谢谢!
最佳答案
我相信这是为字符串数组分配内存的正确方法:
// number of pointers/strings; don't have to cast the result of malloc
char** stringArray = malloc(sizeof(char*) * 2);
// allocate however many chars for each pointer
for(i = 0; i < 2; ++i)
stringArray[i] = malloc(sizeof(char) * 10);
strcpy(stringArray[0], "Hello");
strcpy(stringArray[1], "world!");
printf("%s %s\n", stringArray[0], stringArray[1]);
要释放上述内容,您可以这样做:
for(i = 0; i < 2; ++i)
free(stringArray[i]);
free(stringArray);
关于c - C 中带有字符串的双指针/使用 malloc 指向数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53001732/