Reputation: 443
I am trying to compare patterns. So I have structs which hold the patterns as strings, however I want to be able to build a string and store the VALUE of that string in the struct. At the moment, I am only copying the address of my string.
typedef struct
{
int emp;
char *context;
int numOnes;
int numZeros;
}Pattern;
char *patt, str[t+1];
patt = str;
while(count<t){
//printf("Stream: %d\n", stream[end]);
if(stream[end] == 1){
patt[count]= '1';
//writeBit(1);
}
else{
patt[count]='0';
//writeBit(0);
}
end--;
count++;
}
patt[count]=0;//building string
if(found == 0){//if pattern doesnt exist, add it in
patterns[patternsIndex].context = patt; //NEED HELP HERE. This copies the address not the actual value, which is what i need
patterns[patternsIndex].emp = 1;
prediction = 0;
checkPredict(prediction,stream[end],patternsIndex);
patternsIndex++;
found =1;
}
Upvotes: 0
Views: 108
Reputation: 121961
To avoid making Pattern.context
a fixed size array and to be certain there is enough space to copy into you will need to dynamically allocate memory for Pattern.context
to store a copy of patt
. Either:
use malloc()
(remembering to allocate strlen(patt) + 1
for the null terminator) and strcpy()
:
patterns[patternsIndex].context = malloc(strlen(patt) + 1);
if (patterns[patternsIndex].context)
{
strcpy(patterns[patternsIndex].context, patt);
}
use strdup()
:
patterns[patternsIndex].context = strdup(patt);
In either case, remember to free()
the string copy when no longer required:
free(patterns[patternsIndex].context);
Upvotes: 1
Reputation: 93636
If you mean you want to take the string "14" and make it be a number with the value of 14, then look at the atoi
standard function.
Upvotes: 1