c programming, memory lost after reading file












0















This is part of my c code, the program is to read a file of keywords separated by lines and store them into an array of string.....



int keyno = 4;
char *keywords[keyno];
char var[100];
i=0;
while(fgets(var, sizeof(var), k)!=NULL){ //k is the file
printf("var: %s", var);
if(i>0)
keywords[i-1]=var;
printf("keyword: %s", keywords[i-1]);
i++;
}

for (i=0; i<keyno;i++)
printf("keyword: %s", keywords[i]);


result:



var:
keyword: (null)
var: abc
keyword: abc
var: def
keyword: def
var: ghi
keyword:ghi
var: jkl
keyword: jkl
var:
keyword: @-g(?)

keyword: @-g(?) keyword: @-g(?) keyword: @-g(?) keyword: @-g(?)


why the keywords are gone in the forloop...? what line should i add?










share|improve this question























  • The pointers of keywords char pointer array pointing to same variable var. Hence, you are getting the output as last value of var. Make keywords 2D array and copy the var to keywords array.

    – H.S.
    Nov 24 '18 at 6:21













  • After you now have been given some hints, you might show what you tried (Minimal, Complete, and Verifiable example) and update the code in your question.

    – Swordfish
    Nov 24 '18 at 6:44
















0















This is part of my c code, the program is to read a file of keywords separated by lines and store them into an array of string.....



int keyno = 4;
char *keywords[keyno];
char var[100];
i=0;
while(fgets(var, sizeof(var), k)!=NULL){ //k is the file
printf("var: %s", var);
if(i>0)
keywords[i-1]=var;
printf("keyword: %s", keywords[i-1]);
i++;
}

for (i=0; i<keyno;i++)
printf("keyword: %s", keywords[i]);


result:



var:
keyword: (null)
var: abc
keyword: abc
var: def
keyword: def
var: ghi
keyword:ghi
var: jkl
keyword: jkl
var:
keyword: @-g(?)

keyword: @-g(?) keyword: @-g(?) keyword: @-g(?) keyword: @-g(?)


why the keywords are gone in the forloop...? what line should i add?










share|improve this question























  • The pointers of keywords char pointer array pointing to same variable var. Hence, you are getting the output as last value of var. Make keywords 2D array and copy the var to keywords array.

    – H.S.
    Nov 24 '18 at 6:21













  • After you now have been given some hints, you might show what you tried (Minimal, Complete, and Verifiable example) and update the code in your question.

    – Swordfish
    Nov 24 '18 at 6:44














0












0








0








This is part of my c code, the program is to read a file of keywords separated by lines and store them into an array of string.....



int keyno = 4;
char *keywords[keyno];
char var[100];
i=0;
while(fgets(var, sizeof(var), k)!=NULL){ //k is the file
printf("var: %s", var);
if(i>0)
keywords[i-1]=var;
printf("keyword: %s", keywords[i-1]);
i++;
}

for (i=0; i<keyno;i++)
printf("keyword: %s", keywords[i]);


result:



var:
keyword: (null)
var: abc
keyword: abc
var: def
keyword: def
var: ghi
keyword:ghi
var: jkl
keyword: jkl
var:
keyword: @-g(?)

keyword: @-g(?) keyword: @-g(?) keyword: @-g(?) keyword: @-g(?)


why the keywords are gone in the forloop...? what line should i add?










share|improve this question














This is part of my c code, the program is to read a file of keywords separated by lines and store them into an array of string.....



int keyno = 4;
char *keywords[keyno];
char var[100];
i=0;
while(fgets(var, sizeof(var), k)!=NULL){ //k is the file
printf("var: %s", var);
if(i>0)
keywords[i-1]=var;
printf("keyword: %s", keywords[i-1]);
i++;
}

for (i=0; i<keyno;i++)
printf("keyword: %s", keywords[i]);


result:



var:
keyword: (null)
var: abc
keyword: abc
var: def
keyword: def
var: ghi
keyword:ghi
var: jkl
keyword: jkl
var:
keyword: @-g(?)

keyword: @-g(?) keyword: @-g(?) keyword: @-g(?) keyword: @-g(?)


why the keywords are gone in the forloop...? what line should i add?







c






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 24 '18 at 6:14









ycsjoseycsjose

26




26













  • The pointers of keywords char pointer array pointing to same variable var. Hence, you are getting the output as last value of var. Make keywords 2D array and copy the var to keywords array.

    – H.S.
    Nov 24 '18 at 6:21













  • After you now have been given some hints, you might show what you tried (Minimal, Complete, and Verifiable example) and update the code in your question.

    – Swordfish
    Nov 24 '18 at 6:44



















  • The pointers of keywords char pointer array pointing to same variable var. Hence, you are getting the output as last value of var. Make keywords 2D array and copy the var to keywords array.

    – H.S.
    Nov 24 '18 at 6:21













  • After you now have been given some hints, you might show what you tried (Minimal, Complete, and Verifiable example) and update the code in your question.

    – Swordfish
    Nov 24 '18 at 6:44

















The pointers of keywords char pointer array pointing to same variable var. Hence, you are getting the output as last value of var. Make keywords 2D array and copy the var to keywords array.

– H.S.
Nov 24 '18 at 6:21







The pointers of keywords char pointer array pointing to same variable var. Hence, you are getting the output as last value of var. Make keywords 2D array and copy the var to keywords array.

– H.S.
Nov 24 '18 at 6:21















After you now have been given some hints, you might show what you tried (Minimal, Complete, and Verifiable example) and update the code in your question.

– Swordfish
Nov 24 '18 at 6:44





After you now have been given some hints, you might show what you tried (Minimal, Complete, and Verifiable example) and update the code in your question.

– Swordfish
Nov 24 '18 at 6:44












3 Answers
3






active

oldest

votes


















2














char *keywords[keyno];


is an array of pointers.



In the loop at this line



keywords[i-1]=var;


you make all pointers in keywords point to var. So when you print keywords you actually just print var multiple times.



Instead you could do



char keywords[keyno][100];


and copy like:



strcpy(keywords[i-1], var);





share|improve this answer


























  • The key point is that each of the keyword pointers ends up pointing at the same space for the string, which can only hold the last value stored in it. You're right that a 2D array of characters is one to deal with. Using POSIX function strdup() is also a way to handle it — though the memory would need to be freed too. You can easily implement strdup() if it isn't available: char *strdup(const char *str) { size_t len = strlen(str) + 1; char *dup = malloc(len); if (dup != 0) memmove(dup, str, len); return dup; }.

    – Jonathan Leffler
    Nov 24 '18 at 6:33











  • @ycsjose: I recommend reading up on how to create an MCVE (Minimal, Complete, and Verifiable example). There are all sorts of ways you could be running into compilation errors or warnings, or perhaps runtime errors if you ignore the compile time warnings. We can't begin to guess which clever and non-obvious tricks you've used to fool the compiler — novice programmers are far too clever to be easily predicted by us.

    – Jonathan Leffler
    Nov 24 '18 at 6:39



















0














When you declare an array like this



char* keywords[keyno];


You are declaring an array of pointers to strings. However the pointers need to point somewhere
and each pointer needs to point to a different location.



keywors[i-1]=var;


makes each pointer point to the same address, the address of the array var



to fix this, allocate memory when you get something from the file.



e.g.



keywords[i-1] = malloc(strlen(var)+1); /* allocate memory */
strcpy(keywords[i-1], var); /* copy to the newly allocated memory */


later you need to free that memory



for (int i = 0; i < keyno; ++i)    
free(keywords[i[);


as a precaution make sure all pointers are set to NULL at the beginning in your program since free on an uninitialized pointer is undefined behavior but freeing a NULL pointer is fine.



char* keywords[key];
for (int i = 0; i < keyno; ++i)
keywords[i] = NULL;
...
while(fgets(var, sizeof(var), k)!=NULL){ ... }
...
for (int i = 0; i < keyno; ++i)
free(keywords[i[);





share|improve this answer































    -2














    Simply put, var is just a pointer (it's actually an array, but the difference is not relevant here). It means that:





    • keywords[i-1]=var assigns all array entries to this pointer (so they store the same value).

    • After var becomes something strange (which happens when fgets returns null), all entries also become strange.


    A simple solution is to declare keywords as char keyword[num][len], IIRC, and read directly inside keyword[i].






    share|improve this answer





















    • 2





      No; var is defined as char var[100]; so it is not a pointer. It easily becomes a pointer, but it is an array, not a pointer.

      – Jonathan Leffler
      Nov 24 '18 at 6:30











    • Well, this is why I said "simply put". The difference is irrelevant here.

      – dyukha
      Nov 24 '18 at 6:32











    • @dyukha Why not just do it right(tm)?

      – Swordfish
      Nov 24 '18 at 6:33






    • 1





      Misleading people who are struggling with pointers and arrays is not, IMO, helpful. All else apart, if var were just a pointer, you'd have to worry about the storage it points out. At least with an array, you don't have to deal with that detail. That is a crucial and major difference between a pointer and an array.

      – Jonathan Leffler
      Nov 24 '18 at 6:34








    • 1





      @dyukha Because it's irrelevant – No, spreading misinformation (knowingly!!) is hardly irrelevant but a crime against every poor soul that happens to read it.

      – Swordfish
      Nov 24 '18 at 6:38













    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455675%2fc-programming-memory-lost-after-reading-file%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    char *keywords[keyno];


    is an array of pointers.



    In the loop at this line



    keywords[i-1]=var;


    you make all pointers in keywords point to var. So when you print keywords you actually just print var multiple times.



    Instead you could do



    char keywords[keyno][100];


    and copy like:



    strcpy(keywords[i-1], var);





    share|improve this answer


























    • The key point is that each of the keyword pointers ends up pointing at the same space for the string, which can only hold the last value stored in it. You're right that a 2D array of characters is one to deal with. Using POSIX function strdup() is also a way to handle it — though the memory would need to be freed too. You can easily implement strdup() if it isn't available: char *strdup(const char *str) { size_t len = strlen(str) + 1; char *dup = malloc(len); if (dup != 0) memmove(dup, str, len); return dup; }.

      – Jonathan Leffler
      Nov 24 '18 at 6:33











    • @ycsjose: I recommend reading up on how to create an MCVE (Minimal, Complete, and Verifiable example). There are all sorts of ways you could be running into compilation errors or warnings, or perhaps runtime errors if you ignore the compile time warnings. We can't begin to guess which clever and non-obvious tricks you've used to fool the compiler — novice programmers are far too clever to be easily predicted by us.

      – Jonathan Leffler
      Nov 24 '18 at 6:39
















    2














    char *keywords[keyno];


    is an array of pointers.



    In the loop at this line



    keywords[i-1]=var;


    you make all pointers in keywords point to var. So when you print keywords you actually just print var multiple times.



    Instead you could do



    char keywords[keyno][100];


    and copy like:



    strcpy(keywords[i-1], var);





    share|improve this answer


























    • The key point is that each of the keyword pointers ends up pointing at the same space for the string, which can only hold the last value stored in it. You're right that a 2D array of characters is one to deal with. Using POSIX function strdup() is also a way to handle it — though the memory would need to be freed too. You can easily implement strdup() if it isn't available: char *strdup(const char *str) { size_t len = strlen(str) + 1; char *dup = malloc(len); if (dup != 0) memmove(dup, str, len); return dup; }.

      – Jonathan Leffler
      Nov 24 '18 at 6:33











    • @ycsjose: I recommend reading up on how to create an MCVE (Minimal, Complete, and Verifiable example). There are all sorts of ways you could be running into compilation errors or warnings, or perhaps runtime errors if you ignore the compile time warnings. We can't begin to guess which clever and non-obvious tricks you've used to fool the compiler — novice programmers are far too clever to be easily predicted by us.

      – Jonathan Leffler
      Nov 24 '18 at 6:39














    2












    2








    2







    char *keywords[keyno];


    is an array of pointers.



    In the loop at this line



    keywords[i-1]=var;


    you make all pointers in keywords point to var. So when you print keywords you actually just print var multiple times.



    Instead you could do



    char keywords[keyno][100];


    and copy like:



    strcpy(keywords[i-1], var);





    share|improve this answer















    char *keywords[keyno];


    is an array of pointers.



    In the loop at this line



    keywords[i-1]=var;


    you make all pointers in keywords point to var. So when you print keywords you actually just print var multiple times.



    Instead you could do



    char keywords[keyno][100];


    and copy like:



    strcpy(keywords[i-1], var);






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 24 '18 at 7:04

























    answered Nov 24 '18 at 6:23









    43864274386427

    21.1k31845




    21.1k31845













    • The key point is that each of the keyword pointers ends up pointing at the same space for the string, which can only hold the last value stored in it. You're right that a 2D array of characters is one to deal with. Using POSIX function strdup() is also a way to handle it — though the memory would need to be freed too. You can easily implement strdup() if it isn't available: char *strdup(const char *str) { size_t len = strlen(str) + 1; char *dup = malloc(len); if (dup != 0) memmove(dup, str, len); return dup; }.

      – Jonathan Leffler
      Nov 24 '18 at 6:33











    • @ycsjose: I recommend reading up on how to create an MCVE (Minimal, Complete, and Verifiable example). There are all sorts of ways you could be running into compilation errors or warnings, or perhaps runtime errors if you ignore the compile time warnings. We can't begin to guess which clever and non-obvious tricks you've used to fool the compiler — novice programmers are far too clever to be easily predicted by us.

      – Jonathan Leffler
      Nov 24 '18 at 6:39



















    • The key point is that each of the keyword pointers ends up pointing at the same space for the string, which can only hold the last value stored in it. You're right that a 2D array of characters is one to deal with. Using POSIX function strdup() is also a way to handle it — though the memory would need to be freed too. You can easily implement strdup() if it isn't available: char *strdup(const char *str) { size_t len = strlen(str) + 1; char *dup = malloc(len); if (dup != 0) memmove(dup, str, len); return dup; }.

      – Jonathan Leffler
      Nov 24 '18 at 6:33











    • @ycsjose: I recommend reading up on how to create an MCVE (Minimal, Complete, and Verifiable example). There are all sorts of ways you could be running into compilation errors or warnings, or perhaps runtime errors if you ignore the compile time warnings. We can't begin to guess which clever and non-obvious tricks you've used to fool the compiler — novice programmers are far too clever to be easily predicted by us.

      – Jonathan Leffler
      Nov 24 '18 at 6:39

















    The key point is that each of the keyword pointers ends up pointing at the same space for the string, which can only hold the last value stored in it. You're right that a 2D array of characters is one to deal with. Using POSIX function strdup() is also a way to handle it — though the memory would need to be freed too. You can easily implement strdup() if it isn't available: char *strdup(const char *str) { size_t len = strlen(str) + 1; char *dup = malloc(len); if (dup != 0) memmove(dup, str, len); return dup; }.

    – Jonathan Leffler
    Nov 24 '18 at 6:33





    The key point is that each of the keyword pointers ends up pointing at the same space for the string, which can only hold the last value stored in it. You're right that a 2D array of characters is one to deal with. Using POSIX function strdup() is also a way to handle it — though the memory would need to be freed too. You can easily implement strdup() if it isn't available: char *strdup(const char *str) { size_t len = strlen(str) + 1; char *dup = malloc(len); if (dup != 0) memmove(dup, str, len); return dup; }.

    – Jonathan Leffler
    Nov 24 '18 at 6:33













    @ycsjose: I recommend reading up on how to create an MCVE (Minimal, Complete, and Verifiable example). There are all sorts of ways you could be running into compilation errors or warnings, or perhaps runtime errors if you ignore the compile time warnings. We can't begin to guess which clever and non-obvious tricks you've used to fool the compiler — novice programmers are far too clever to be easily predicted by us.

    – Jonathan Leffler
    Nov 24 '18 at 6:39





    @ycsjose: I recommend reading up on how to create an MCVE (Minimal, Complete, and Verifiable example). There are all sorts of ways you could be running into compilation errors or warnings, or perhaps runtime errors if you ignore the compile time warnings. We can't begin to guess which clever and non-obvious tricks you've used to fool the compiler — novice programmers are far too clever to be easily predicted by us.

    – Jonathan Leffler
    Nov 24 '18 at 6:39













    0














    When you declare an array like this



    char* keywords[keyno];


    You are declaring an array of pointers to strings. However the pointers need to point somewhere
    and each pointer needs to point to a different location.



    keywors[i-1]=var;


    makes each pointer point to the same address, the address of the array var



    to fix this, allocate memory when you get something from the file.



    e.g.



    keywords[i-1] = malloc(strlen(var)+1); /* allocate memory */
    strcpy(keywords[i-1], var); /* copy to the newly allocated memory */


    later you need to free that memory



    for (int i = 0; i < keyno; ++i)    
    free(keywords[i[);


    as a precaution make sure all pointers are set to NULL at the beginning in your program since free on an uninitialized pointer is undefined behavior but freeing a NULL pointer is fine.



    char* keywords[key];
    for (int i = 0; i < keyno; ++i)
    keywords[i] = NULL;
    ...
    while(fgets(var, sizeof(var), k)!=NULL){ ... }
    ...
    for (int i = 0; i < keyno; ++i)
    free(keywords[i[);





    share|improve this answer




























      0














      When you declare an array like this



      char* keywords[keyno];


      You are declaring an array of pointers to strings. However the pointers need to point somewhere
      and each pointer needs to point to a different location.



      keywors[i-1]=var;


      makes each pointer point to the same address, the address of the array var



      to fix this, allocate memory when you get something from the file.



      e.g.



      keywords[i-1] = malloc(strlen(var)+1); /* allocate memory */
      strcpy(keywords[i-1], var); /* copy to the newly allocated memory */


      later you need to free that memory



      for (int i = 0; i < keyno; ++i)    
      free(keywords[i[);


      as a precaution make sure all pointers are set to NULL at the beginning in your program since free on an uninitialized pointer is undefined behavior but freeing a NULL pointer is fine.



      char* keywords[key];
      for (int i = 0; i < keyno; ++i)
      keywords[i] = NULL;
      ...
      while(fgets(var, sizeof(var), k)!=NULL){ ... }
      ...
      for (int i = 0; i < keyno; ++i)
      free(keywords[i[);





      share|improve this answer


























        0












        0








        0







        When you declare an array like this



        char* keywords[keyno];


        You are declaring an array of pointers to strings. However the pointers need to point somewhere
        and each pointer needs to point to a different location.



        keywors[i-1]=var;


        makes each pointer point to the same address, the address of the array var



        to fix this, allocate memory when you get something from the file.



        e.g.



        keywords[i-1] = malloc(strlen(var)+1); /* allocate memory */
        strcpy(keywords[i-1], var); /* copy to the newly allocated memory */


        later you need to free that memory



        for (int i = 0; i < keyno; ++i)    
        free(keywords[i[);


        as a precaution make sure all pointers are set to NULL at the beginning in your program since free on an uninitialized pointer is undefined behavior but freeing a NULL pointer is fine.



        char* keywords[key];
        for (int i = 0; i < keyno; ++i)
        keywords[i] = NULL;
        ...
        while(fgets(var, sizeof(var), k)!=NULL){ ... }
        ...
        for (int i = 0; i < keyno; ++i)
        free(keywords[i[);





        share|improve this answer













        When you declare an array like this



        char* keywords[keyno];


        You are declaring an array of pointers to strings. However the pointers need to point somewhere
        and each pointer needs to point to a different location.



        keywors[i-1]=var;


        makes each pointer point to the same address, the address of the array var



        to fix this, allocate memory when you get something from the file.



        e.g.



        keywords[i-1] = malloc(strlen(var)+1); /* allocate memory */
        strcpy(keywords[i-1], var); /* copy to the newly allocated memory */


        later you need to free that memory



        for (int i = 0; i < keyno; ++i)    
        free(keywords[i[);


        as a precaution make sure all pointers are set to NULL at the beginning in your program since free on an uninitialized pointer is undefined behavior but freeing a NULL pointer is fine.



        char* keywords[key];
        for (int i = 0; i < keyno; ++i)
        keywords[i] = NULL;
        ...
        while(fgets(var, sizeof(var), k)!=NULL){ ... }
        ...
        for (int i = 0; i < keyno; ++i)
        free(keywords[i[);






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 24 '18 at 7:19









        AndersAnders

        30.2k64872




        30.2k64872























            -2














            Simply put, var is just a pointer (it's actually an array, but the difference is not relevant here). It means that:





            • keywords[i-1]=var assigns all array entries to this pointer (so they store the same value).

            • After var becomes something strange (which happens when fgets returns null), all entries also become strange.


            A simple solution is to declare keywords as char keyword[num][len], IIRC, and read directly inside keyword[i].






            share|improve this answer





















            • 2





              No; var is defined as char var[100]; so it is not a pointer. It easily becomes a pointer, but it is an array, not a pointer.

              – Jonathan Leffler
              Nov 24 '18 at 6:30











            • Well, this is why I said "simply put". The difference is irrelevant here.

              – dyukha
              Nov 24 '18 at 6:32











            • @dyukha Why not just do it right(tm)?

              – Swordfish
              Nov 24 '18 at 6:33






            • 1





              Misleading people who are struggling with pointers and arrays is not, IMO, helpful. All else apart, if var were just a pointer, you'd have to worry about the storage it points out. At least with an array, you don't have to deal with that detail. That is a crucial and major difference between a pointer and an array.

              – Jonathan Leffler
              Nov 24 '18 at 6:34








            • 1





              @dyukha Because it's irrelevant – No, spreading misinformation (knowingly!!) is hardly irrelevant but a crime against every poor soul that happens to read it.

              – Swordfish
              Nov 24 '18 at 6:38


















            -2














            Simply put, var is just a pointer (it's actually an array, but the difference is not relevant here). It means that:





            • keywords[i-1]=var assigns all array entries to this pointer (so they store the same value).

            • After var becomes something strange (which happens when fgets returns null), all entries also become strange.


            A simple solution is to declare keywords as char keyword[num][len], IIRC, and read directly inside keyword[i].






            share|improve this answer





















            • 2





              No; var is defined as char var[100]; so it is not a pointer. It easily becomes a pointer, but it is an array, not a pointer.

              – Jonathan Leffler
              Nov 24 '18 at 6:30











            • Well, this is why I said "simply put". The difference is irrelevant here.

              – dyukha
              Nov 24 '18 at 6:32











            • @dyukha Why not just do it right(tm)?

              – Swordfish
              Nov 24 '18 at 6:33






            • 1





              Misleading people who are struggling with pointers and arrays is not, IMO, helpful. All else apart, if var were just a pointer, you'd have to worry about the storage it points out. At least with an array, you don't have to deal with that detail. That is a crucial and major difference between a pointer and an array.

              – Jonathan Leffler
              Nov 24 '18 at 6:34








            • 1





              @dyukha Because it's irrelevant – No, spreading misinformation (knowingly!!) is hardly irrelevant but a crime against every poor soul that happens to read it.

              – Swordfish
              Nov 24 '18 at 6:38
















            -2












            -2








            -2







            Simply put, var is just a pointer (it's actually an array, but the difference is not relevant here). It means that:





            • keywords[i-1]=var assigns all array entries to this pointer (so they store the same value).

            • After var becomes something strange (which happens when fgets returns null), all entries also become strange.


            A simple solution is to declare keywords as char keyword[num][len], IIRC, and read directly inside keyword[i].






            share|improve this answer















            Simply put, var is just a pointer (it's actually an array, but the difference is not relevant here). It means that:





            • keywords[i-1]=var assigns all array entries to this pointer (so they store the same value).

            • After var becomes something strange (which happens when fgets returns null), all entries also become strange.


            A simple solution is to declare keywords as char keyword[num][len], IIRC, and read directly inside keyword[i].







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 24 '18 at 6:50

























            answered Nov 24 '18 at 6:24









            dyukhadyukha

            582511




            582511








            • 2





              No; var is defined as char var[100]; so it is not a pointer. It easily becomes a pointer, but it is an array, not a pointer.

              – Jonathan Leffler
              Nov 24 '18 at 6:30











            • Well, this is why I said "simply put". The difference is irrelevant here.

              – dyukha
              Nov 24 '18 at 6:32











            • @dyukha Why not just do it right(tm)?

              – Swordfish
              Nov 24 '18 at 6:33






            • 1





              Misleading people who are struggling with pointers and arrays is not, IMO, helpful. All else apart, if var were just a pointer, you'd have to worry about the storage it points out. At least with an array, you don't have to deal with that detail. That is a crucial and major difference between a pointer and an array.

              – Jonathan Leffler
              Nov 24 '18 at 6:34








            • 1





              @dyukha Because it's irrelevant – No, spreading misinformation (knowingly!!) is hardly irrelevant but a crime against every poor soul that happens to read it.

              – Swordfish
              Nov 24 '18 at 6:38
















            • 2





              No; var is defined as char var[100]; so it is not a pointer. It easily becomes a pointer, but it is an array, not a pointer.

              – Jonathan Leffler
              Nov 24 '18 at 6:30











            • Well, this is why I said "simply put". The difference is irrelevant here.

              – dyukha
              Nov 24 '18 at 6:32











            • @dyukha Why not just do it right(tm)?

              – Swordfish
              Nov 24 '18 at 6:33






            • 1





              Misleading people who are struggling with pointers and arrays is not, IMO, helpful. All else apart, if var were just a pointer, you'd have to worry about the storage it points out. At least with an array, you don't have to deal with that detail. That is a crucial and major difference between a pointer and an array.

              – Jonathan Leffler
              Nov 24 '18 at 6:34








            • 1





              @dyukha Because it's irrelevant – No, spreading misinformation (knowingly!!) is hardly irrelevant but a crime against every poor soul that happens to read it.

              – Swordfish
              Nov 24 '18 at 6:38










            2




            2





            No; var is defined as char var[100]; so it is not a pointer. It easily becomes a pointer, but it is an array, not a pointer.

            – Jonathan Leffler
            Nov 24 '18 at 6:30





            No; var is defined as char var[100]; so it is not a pointer. It easily becomes a pointer, but it is an array, not a pointer.

            – Jonathan Leffler
            Nov 24 '18 at 6:30













            Well, this is why I said "simply put". The difference is irrelevant here.

            – dyukha
            Nov 24 '18 at 6:32





            Well, this is why I said "simply put". The difference is irrelevant here.

            – dyukha
            Nov 24 '18 at 6:32













            @dyukha Why not just do it right(tm)?

            – Swordfish
            Nov 24 '18 at 6:33





            @dyukha Why not just do it right(tm)?

            – Swordfish
            Nov 24 '18 at 6:33




            1




            1





            Misleading people who are struggling with pointers and arrays is not, IMO, helpful. All else apart, if var were just a pointer, you'd have to worry about the storage it points out. At least with an array, you don't have to deal with that detail. That is a crucial and major difference between a pointer and an array.

            – Jonathan Leffler
            Nov 24 '18 at 6:34







            Misleading people who are struggling with pointers and arrays is not, IMO, helpful. All else apart, if var were just a pointer, you'd have to worry about the storage it points out. At least with an array, you don't have to deal with that detail. That is a crucial and major difference between a pointer and an array.

            – Jonathan Leffler
            Nov 24 '18 at 6:34






            1




            1





            @dyukha Because it's irrelevant – No, spreading misinformation (knowingly!!) is hardly irrelevant but a crime against every poor soul that happens to read it.

            – Swordfish
            Nov 24 '18 at 6:38







            @dyukha Because it's irrelevant – No, spreading misinformation (knowingly!!) is hardly irrelevant but a crime against every poor soul that happens to read it.

            – Swordfish
            Nov 24 '18 at 6:38




















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455675%2fc-programming-memory-lost-after-reading-file%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            Refactoring coordinates for Minecraft Pi buildings written in Python