Edit: solution was to use strdup()
I have re-asked my question.
How to create to a new string to use as a key everytime I call a function?
I want to a fresh variable char[] newer everytime my function is called. The reason is because I set my key as newer in a global hashmap. I don't want keys being modified everytime I call the function and modify newer.
#include <stdio.h>
#include <string.h>
void new(){
char newer[45];
printf("%s
", newer);
strncat(newer,"hi",1235);
}
int main()
{
int i = 0;
for (i = 0; i < 6; i++){
new();
}
}
My current output is
hi
hihi
hihihi
hihihihi
hihihihihi
but I want it to be
hi
hi
hi
hi
hi
Edit: I forgot to mention the purpose of my code.
I'm not able to post the code completely since it's a school project. Basically let's say I have a global hashmap that takes (key,value) pairs. Everytime I call the new()
it should add a new entry to the hashmap. For example I have a function add
which is supposed to add (key = newer, value = "something")
to the global hashmap. I want hashmap = { key1="hi":value1="stuff",key2="hihi":value2=stuff2"}
after 2 calls to the function.
For some reason my hashmap ends up being {key1="hi:value1="stuff"}
after 1 call and then {key1="hihi":value1="stuff",key2="hihi":value2="stuff2"}
after 2 calls. The reason is because the key1 = newer
and key2 = newer
so thus key1=key2
. This means that everytime I modify variable newer
in a function call, it literally changes my previous key's values
For example in python I could do the following since everytime I call newer, it is a fresh variable that has no relationship with previous calls using newer.
def new(i,diction):
newer = "hi" * i
diction[newer] = "stuff" + str(i)
diction = {}
for i in range(10):
new(i,diction)
print(diction)
Essentially result is
{'': 'stuff0', 'hihi': 'stuff2', 'hihihihihihi': 'stuff6', 'hi': 'stuff1', 'hihihi': 'stuff3', 'hihihihi': 'stuff4', 'hihihihihihihi': 'stuff7
', 'hihihihihihihihihi': 'stuff9', 'hihihihihihihihi': 'stuff8', 'hihihihihi': 'stuff5'}
I want to ask how to do the same thing in C
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…