c - 如何将指针变为指针到指针?

标签 c

我重写了之前的程序,想把*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/

相关文章:

c - 如何获取unsigned char的每一位的值?

c++ - 在 WIN32 上编译,无需 Windows.h

c - 在这种情况下哪种操作系统概念应该更好

c - 允许线程降低其自身 nice 的最便携(在 *nix 中)方式

c - 格式说明符 : %u vs %d in C

c++ - 运行时检查失败 #2 - 变量 'cid1' 周围的堆栈已损坏

c - 如何使用 FILE 来理解给定的代码?

c - 泰勒级数函数 e^x

c - 初始化 typedef 结构体的 typedef 字段

c - 通过按位运算获取两个数中的较大者