简体   繁体   中英

How to get the value of a string from char* not the address

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;
} 

如果你的意思是你想取字符串“14”并使它成为一个值为14的数字,那么看看atoi标准函数。

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM