user3600107
user3600107

Reputation: 346

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

Upvotes: 1

Views: 143

Answers (3)

sarathrami
sarathrami

Reputation: 356

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

`

Upvotes: 0

P.P
P.P

Reputation: 121387

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.

Upvotes: 3

Mark Madej
Mark Madej

Reputation: 1912

To change "bill" to "ball" in your example I think this would do it:

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

Upvotes: 0

Related Questions