我重写了之前的程序,想把*dirty改成**dirty。你能给我一些建议吗? 这是我的代码:
void clean(char *dirty)
{
int i = 0, j = 0;
char *temp;
temp = strdup(dirty);
if(NULL == temp)
{
printf("strdup(), failed");
return;
}
while(i < strlen(temp))
{
if(isalpha(temp[i]) || isspace(temp[i]) || temp[i] == '?'
|| temp[i] == '.' || temp[i] == '!' || temp[i] == ',')
{
dirty[j] = temp[i];
j++;
}
i++;
}
dirty[j] = '\0';
free(temp);
}
更改 main() 的一部分,我遇到了一些问题,与我的 friend 一起,我们创建了这个:
int main(int argc, char** argv)
{
FILE* fp;
char** tab;
int i = 0;
int lines = 0;
int length = 10;
if(argc != 2)
{
printf("Incorrent syntax! Use ./name_of_program input_file\n");
return 1;
}
if(!(fp = fopen(argv[1],"r")))
{
printf("Could not open the file! Please try again!\n");
return 2;
}
tab = (char**)malloc(length*(sizeof(char*)));
if(!tab)
{
printf("Could not allocate memory!\n");
free(tab);
return 3;
}
while(!feof(fp))
{
tab[i] = getNumber(fp);
if(i >= length)
{
length += 10;
tab = (char**)realloc(tab, sizeof(char*));
if(tab == NULL)
{
free(tab);
return 5;
}
}
if(tab[i] == NULL)
{
printf("Incorrect character in the infile! Terminating\n");
free(tab);
return 4;
...
最佳答案
根据你想做什么,首先,在你的 main 中记下这一点
tab = (char**)realloc(tab, sizeof(char*));
因此,您将 10 个指针数组重新分配到大小为 1 的指针数组中。似乎不正确(如果您提供更多,例如 length* sizeof ,则 realloc 会将给定指针分配的内存更改为提供的大小。 ..您将增加数组大小,但您不会丢失所有数据。
现在,如果您想将“clean”函数应用于字符串数组(char *),那么您应该包括该数组的当前最大大小。我建议你这样做,更快。
void clean_All(char ** strings, int size)
{
int i;
if (strings == NULL)
return;
for(i = 0; i < size; i++) {
if (strings[i] == NULL)
return;
clean(strings[i]);
}
return;
}
关于c - 如何将指针变为指针到指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18903159/