Search code examples
cmemcpyc-strings

Having trouble with memcpy


Code I'm using:

char** list  
char** final;
char* target;
char* replace;
int wCounter, cCounter, i, hashCounter = 0, addLetter = 0;
int copyWord, countChars, numOfWords, finalWords = 0, temp;

//stuff here

for(wCounter; wCounter < temp + numOfWords; wCounter++, finalWords++)
{
    printf("Original string: %s\n", list[wCounter+1]);
    final[finalWords] = strstr(list[wCounter+1], target);

    if(final[finalWords] != NULL)
        memcpy(final[finalWords], replace, strlen(target));

    printf("Final string: %s\n\n", final[finalWords]);
}

//stuff here

My program output:

Target string = h   Replacement string = j

Original string: hello
   Final string: jello //works!!!

Original string: happy birthday
   Final string: jappy birthday  // should be jappy birtjday

Target string = ra  Replacement string = ar

Original string: radar
   Final string: ardar   //works!!!

Original string: are you ready
   Final string: (null)  //awkward

Original string: pirate radio rating
   Final string: arte radio rating //should be piarte ardio arting

Target string = x   Replacement string = zz

Original string: exit
   Final string: zit   //should be zzit

Original string: x-ray
   Final string: z-ray  //should be zz-ray

Original string: xerox
   Final string: zerox //should be zzerox

My program has a target string ('h' for example) It also has a replacement string('j' for example)

everytime it sees an 'h' it should replace it with a 'j'

happy birthday should be jappy birtjday.


Solution

  • Ok, there are a several issues with your code.

    First of all: strstr returns only the pointer to the FIRST occurence of the sequence to match (see here for details). So you never get the pointers to the second or third occurence. You need to rework your concept here.

    Secondly: Using memcopy to replace something is only working if the replacement is of the same length as the part to be replaced. Consider following example:

    Address:  0123456789ABCD
    Original: This is a test
    Target: is
    Replacement foo
    

    Notice that the replacement exceeds the length of the target. Now what happens in your code? strstr returns address 2. You pass now this pointer to memcpy. What you get is the following string: Thfo is a test

    Notice that the second 'o' of 'foo' is missing. This is because you only copy as many bytes as the target string has. If you would have copied as many bytes as the replacement has, you would have ended up with a string like Thfoois a test. Barely better isn't it?

    I'd recommend to think again about your solution concept. Maybe a better approach is to "tokenize" the string by the occurence of your target string and concatenate the elements in order to get the desired result.