【问题标题】:C Double pointer Char is printing NULL. Don't Know what's going wrong?C 双指针 Char 正在打印 NULL。不知道怎么回事?
【发布时间】:2014-09-26 00:23:23
【问题描述】:

这是显示读取的字符串的显示函数。

void print(char **s,int T)
{   

    while(*s)
    {

        printf("i: String : %s\n",*s++);

    }

}



int main()


{



int T =0,i=0;

    char ** s, *c;
    printf("Enter number of Testcases:\n");
    scanf("%d",&T);
    s = (char **)malloc(T*sizeof(char *));
    printf("Size allocated : %lu\n",sizeof(s));

    while(i++ < T)
    {
        s= (char *)malloc(10000*sizeof(char));
        scanf("%s",*s++);

    }
    print(s,T);


    return 0;
}

【问题讨论】:

  • 1)sizeof(s) 大小为char **,未分配大小。 2) s 重写 s= (char *)malloc(10000*sizeof(char)); 3) print(s,T); : s 是最后一个或某处。
  • 4) while(*s) : 它没有被额外保护为 NULL。

标签: c double-pointer char-pointer


【解决方案1】:

这段代码:

s= (char *)malloc(10000*sizeof(char));
scanf("%s", *s++);

应该是:

s[i-1] = malloc(10000);
scanf("%9999s", s[i-1];

我建议重构循环,以便在循环中使用i 而不是i-1

你最初的想法行不通,因为:

  • 您在malloc 中写了s 而不是*s
  • 一旦这个循环结束,s 指向列表的末尾;但是您随后将 s 传递给您的打印函数,该函数需要一个指向列表开头的指针

此外,print 函数当前迭代数组的末尾(如果你按照我上面的建议正确传递了s,那就是)。相反,它应该在打印 T 字符串后停止。您可能应该将呼叫更改为 print(s, i); ;更新print 以基于int 循环,并添加对scanf 失败的检查。

【讨论】:

  • 我按照您的建议修改了我的代码。但它的行为仍然相同。
  • i=T; while(i > 0) { s[i-1]= (char *)malloc(10000*sizeof(char)); scanf("%9999s",s[i-1]); printf("%s\n",s[i-1]);我++; }
  • 您刚刚在该评论中发布的代码会注销数组的末尾。您希望i0 运行到T-1,并访问s[i]。您的代码实际上有 iT 运行到无穷大。
  • 写循环的常用方法是for (int i = 0; i &lt; T; ++i)
【解决方案2】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void print(char **s,int T){
    int i=0;
    while(T--){
        printf("%d: String : %s\n", ++i, *s++);
    }
}

int main(){
    int T =0, i=0;
    char **s, **p;
    size_t size;

    printf("Enter number of Testcases:\n");
    scanf("%d",&T);
    p = s = (char **)malloc(size=T*sizeof(char *));
    //printf("Size allocated : %zu\n", size);
    printf("Size allocated : %lu\n", (unsigned long)size);

    while(i++ < T){
        char tmp[10000];
        scanf("%9999s", tmp);
        *p++ = strdup(tmp);//strdup is not standard function
    }
    print(s,T);
    //deallocate
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多