简体   繁体   中英

How to Change individual strings in an array of strings in C?

I have pasted an example variable below so that I can point out what I need to change. If you look there is four strings in this array how do I change one (non-manual) of the letters of one of the strings. If anyone can solve this I would appreciate it very much.

char *names[] = {
               "bill",
               "man",
              "test",
              "bob",
};

What you have is an array of pointers, each pointing to a string literal. Modifying string literal is not allowed in standard C and doing so is undefined behaviour .

Depending on your usage and need, 1) you may take a copy of the string and modify it or 2) declare names as an array of arrays (instead of pointers) and modify the array element.

要在您的示例中将“bill”更改为“ball”,我认为这样做:

names[0][1] = 'a';

You could probably use sizeof() and pointers to do it, since every char in memory is linear

Eg: `

//Remove duplicate char in string 'in'
char* rem_dup(char* in){

    int i=0, j=0, pos=0;
    for(;i<strlen(in);i++){
    int charat = *(in+i);
    for(j=i+1;j<strlen(in);j++){
        if(charat == *(in+j)){
        *(in+i) = *(in+j) = -1;
        }
    }

    if(*(in+i) > 0){        
        *(in+pos) = *(in+i);
        pos++;
    }

    }

    *(in+pos) = 0;
    return in;
}

int main(){
    int i=0;
    char str[][100] = {"remove duplicates", "", "aabb", "ab", "a", "abba"};
    for(;i<sizeof(str)/sizeof(char);i+=sizeof(str[0])/sizeof(char)){
    printf("IN :%s\n",(char*)str+i);
    printf("OUT:%s\n", rem_dup((char*)str+i));
    }
    return 0;
}

`

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