Array of structs replacing values over itself

后端 未结 3 1346
有刺的猬
有刺的猬 2020-11-30 15:25

Ok so I have the below code and I am just pulling various things from a file and inputing them in an array of structs, it \"seemingly\" works initially, BUT when I go to pri

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 16:09

    This is a simple misunderstanding of pointers and char arrays (strings). Here are a couple pages that explains them pretty well:

    • http://www.cplusplus.com/doc/tutorial/pointers/
    • http://www.cplusplus.com/doc/tutorial/ntcs/

    In your case, you are setting your struct pointer values equal to the returned pointer from strtok. A lot of those string functions work by putting the result at a certain memory address and returning the pointer to it. The pointer returned is always the same, so all your struct values are going to point to the last result of the strtok call.

    This is why you need strdup (String duplicate). Basically it takes the value at the address given and copies the contents into a new place in memory and returns the value.

提交回复
热议问题