Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 为什么我的双指针会覆盖它的行?_C_Pointers_Malloc_Free - Fatal编程技术网

C 为什么我的双指针会覆盖它的行?

C 为什么我的双指针会覆盖它的行?,c,pointers,malloc,free,C,Pointers,Malloc,Free,我试图一次为每行的每个块输入一个字符,但是发生的情况是最新的一行将覆盖我存储在前一行中的前一个内容。最后,我的所有行都有相同的内容。。有人能解释一下我做错了什么吗 #include<stdio.h> #include<stdlib.h> #include<ctype.h> int main() { int row=0,col=0,i; char c; char **this=NULL; this=calloc(64,size

我试图一次为每行的每个块输入一个字符,但是发生的情况是最新的一行将覆盖我存储在前一行中的前一个内容。最后,我的所有行都有相同的内容。。有人能解释一下我做错了什么吗

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>

int main()
{
    int row=0,col=0,i;
    char c;
    char **this=NULL;

    this=calloc(64,sizeof(char*));


    for(i=0;i<64;++i)
    {
        this[i]=calloc(5,sizeof(char));
        free(this[i]);
    }

    while(c!=EOF)
    {
        c=getchar();
        if(!isspace(c)&&isprint(c))
        {
            if(c==',')
            {
                this[row][col]='\0';
                row++;
                col=0;
            }
            else if(c=='.')
            {
                this[row][col]=c;
                this[row][col+1]='\0';
            }
            else 
            {
            this[row][col]=c;
            //printf("%d,%d\n",row, col);
            //printf("%c\n",this[row][col]);
            //printf("%s\n",this[row]);
            //printf("%s\n",this[row+1]);
            col++;
            }
        }
    }
    printf("string0:%s\n",this[0]);//prints the same thing
    printf("string1:%s\n",this[1]);

    free(this);
    return 0; 
}
#包括
#包括
#包括
int main()
{
int行=0,列=0,i;
字符c;
char**this=NULL;
这=calloc(64,sizeof(char*);

对于代码中的(i=0;i,在
calloc()之后,立即执行

 free(this[i]);
将内存标记为已释放(即不再使用)。然后,稍后您尝试使用内存时,会导致

一旦使用完内存,您就必须释放它。对单个
调用
free()
的好时机就在

  free(this);

打电话。

免费的
有什么事吗(这个[i])
分配后立即使用?分配后对任何指针的使用都是未定义的行为。我知道无论何时分配,我都需要释放它,这样我仍然可以重用空间?但我真的不知道应该在哪里释放它。处理完内存后,您可以释放内存。如果您尝试使用分配的内存(以及指针对象)在free之后,这是一种未定义的行为。如果我不得不猜测你为什么会看到你所看到的,我会说接下来对
calloc()的调用
由于您刚才正在释放,所以一遍又一遍地返回相同的区域。但是,尝试解释未定义的行为是毫无意义的,因为它是未定义的。另外:
char c;
-->
int c;
(但EOF逻辑仍然错误)ohhhh tyty it fixed!