将字符串添加到我的指针数组时,它正在被最后一个覆盖。谁能告诉我,我的错误在哪里?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main (){
int ile = 3;
const char * slowa[ile];
for(int j = 0; j < ile; j++){
char string[30];
gets(string);
slowa[j] = string;
printf ("%s dodalem pierwsza\n",string);
}
for (int i = 0; i < ile; i++) {
printf ("%s numer %d\n",slowa[i],i);
}
return 0;
}
最佳答案
答案就在下面两行代码中:
char string[30];
...
slowa[j] = string;
赋值将 slowa[j]
设置为 same 缓冲区的地址,而不进行复制。因此,您放入缓冲区的最后一件事将被 slowa[]
数组的所有元素引用,直到 j-1
的位置。
为了解决这个问题,在将值存储到slowa
之前制作副本。你可以使用非标准的strdup
,或者使用malloc
+strcpy
:
char string[30];
gets(string);
slowa[j] = malloc(strlen(string)+1);
strcpy(slowa[j], string);
在这两种情况下,您都需要对已分配值的 slowa[]
数组的所有元素调用 free
,以避免内存泄漏。
关于c - 使用qsort在c中指向char *的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40965134/