当前位置: 动力学知识库 > 问答 > 编程问答 >

C Double pointer Char is printing NULL. Don't Know what's going wrong?

问题描述:

This is display function to display the strings read in.

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;

}

网友答案:

This code:

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

should be:

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

I would advise to refactor the loop so that you use i within the loop rather than i-1.

Your original idea doesn't work because:

  • you wrote s instead of *s in the malloc
  • once this loop finishes, s points to the end of the list; but you then pass s to your print function which is expecting a pointer to the start of the list

Further, the print function currently iterates off the end of the array (if you pass s correctly as I suggest above, that is). Instead, it should stop after it has printed T strings. You should probably change the call to print(s, i); ; update print to loop based on that int, and also add a check for scanf failure.

网友答案:
#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;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: