1
#define OK 0
#define MAXSTRING 200
#define NUMBER 10
#define MALLOC_ERROR 2

int main(int argc, char** argv) {

    char **B = (char**)malloc(sizeof(char*)*NUMBER);
    char buffer[MAXSTRING];
    int i, strings = 0, arraysize = NUMBER;

    if (( B = ( char**)malloc(sizeof(char*)*NUMBER))==NULL) {
        printf("initial malloc error\n");
        fflush(stdout);
        exit(MALLOC_ERROR);
    }

    for(int i = 0; i< NUMBER; i++) {
        B[i] = (char*)malloc(sizeof(char)*MAXSTRING);
    }
    while((fgets(buffer,MAXSTRING,stdin))!=NULL) {
        /*
            if(strings+1>arraysize)
            {
                arraysize = 2*arraysize;
                B=realloc(B,(arraysize)*sizeof(char*));
            }
        */
        buffer[strlen(buffer)-1]='\0';
        B[strings] = buffer;
        printf("%s \n", buffer);
        strings++;
    }


    printf("Read %d strings:\n", strings);
    for (i = 0; i<strings ; i++) {
      printf("\t%s\t %d\n", B[i], (int)strlen(B[i]));
    }
    return 0;
}

When i tried to print the B[i] from the loop,it just outputs the last input of the stdin in all of its positions. I tried testing with normal for loop and it somehow works, but i do not know the cause of the problem. Thanks for the help!! For example, i put "giraffe" as first input, another input "eat", last input"leaves", the loop of B[i] only outputs "leaves"

Alviss Min
  • 79
  • 10

1 Answers1

1

When you do B[string] = bufferyou do not copy the string, you just make a copy of the pointer, you should use strcpy().

Assuming that your string is always \0 terminated, something like that should work strcpy(B[i], buffer);

Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
  • Thanks alot. it works now! :D – Alviss Min Sep 13 '17 at 10:22
  • 1
    `strncpy` is for copying fixed length character arrays. As such each answer that suggest that function *must always* warn about its flakey zero termination behaviour. It's not an issue with code in question, but may be when code is modified later on. – user694733 Sep 13 '17 at 10:35
  • Indeed. `strncpy` is a dangerous function and should not be used. In particular we shouldn't recommend it to beginners. Use `strcpy` or `memcpy` instead. https://stackoverflow.com/questions/2114896/why-are-strlcpy-and-strlcat-considered-insecure – Lundin Sep 13 '17 at 11:16
  • @Lundin I updated with use of strcpy :) – Cédric Julien Sep 13 '17 at 12:27