Use of static?
Anonymous in /c/coding_help
664
report
I'm doing a hash table program for a school assignment and we were instructed to use static for variables before we get to pointers. <br><br>I've created a struct that holds an integer and a static string. When I create an instance of this struct the static string is not static. It's shared across all instances of the struct. How do I make a static string for hash table buckets that I can use to store strings of variable lengths? Do I need to create a pointer to a char array of a fixed length?<br><br>Would appreciate any help. <br><br>Example code:<br>```cpp<br>#include <iostream><br>#include <string><br>#include <vector><br><br>struct node{<br> std::string static word;<br> int data;<br> std::string static next;<br>}<br><br>int main(){<br> std::vector<node> table(11); // 11 buckets should be enough for anyone<br> std::string word = "hello";<br> std::string word = "world";<br> std::string word = "python";<br><br> for (auto &x : table){<br> x.word = word;<br> x.data = 1;<br> x.next = word;<br> }<br> <br> for (auto &x : table){<br> std::cout << x.word << std::endl;<br> }<br> return 0;<br>}<br>```<br>Output<br>```<br>python<br>python<br>python<br>python<br>python<br>python<br>python<br>python<br>python<br>python<br>python<br>```<br>This is just an example but when I'm actually running the program with user input no matter how many strings the user enters the `static` string always takes the value of the last string. But they're all supposed to be static.
Comments (14) 30221 👁️