0

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;
} 
1
  • You may be looking for strcpy(). If you start off with just a pointer, rather than an array, you'll also need to allocate memory for it before you copy, since you can't copy a string until you have some valid memory to copy it into.
    – Crowman
    Apr 25, 2014 at 15:29

2 Answers 2

1

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);
1
  • Could you elaborate please? Apr 25, 2014 at 15:32
1

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.