0

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;
}
StilesCrisis
  • 15,972
  • 4
  • 39
  • 62
Sandeep
  • 13
  • 4
  • 1)`sizeof(s)` size of `char **`, not allocated size. 2) `s` rewrite by `s= (char *)malloc(10000*sizeof(char));` 3) `print(s,T);` : `s` is next of last or somewhere. – BLUEPIXY Sep 26 '14 at 00:27
  • 4) `while(*s)` : It has not been secured extra for NULL. – BLUEPIXY Sep 26 '14 at 00:37

2 Answers2

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.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • I modified my code as you suggested. But still it behaves the same. – Sandeep Sep 26 '14 at 00:43
  • i=T; while(i > 0) { s[i-1]= (char *)malloc(10000*sizeof(char)); scanf("%9999s",s[i-1]); printf("%s\n",s[i-1]); i++; } – Sandeep Sep 26 '14 at 00:44
  • The code you just posted in that comment writes off the end of the array. You want `i` to run from `0` to `T-1`, and access `s[i]`. Your code actually has `i` run from `T` to infinity. – M.M Sep 26 '14 at 00:49
  • The usual way to write a loop is `for (int i = 0; i < T; ++i)` – M.M Sep 26 '14 at 00:50
0
#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;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70