Cannot concatenate strtok's output variable. strcat and strtok

筅森魡賤 提交于 2019-12-08 21:18:33

strcat would work if you used first instead of firstOrig in your loop. No need for mystrcat. Can be simplified to:

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "now # is the time for all # good men to come to the # aid of their     country";
    char delims[] = "# ";
    char result[100] = "";  /* Original size was too small */
    char* token;
    token = strtok(str, delims);
    while(token != NULL) {
        printf("token = '%s'\n", token);
        strcat(result, token);
        token = strtok(NULL, delims);
    }
    printf("%s\n", result);
    return 0;
}

Output:

token = 'now'
token = 'is'
token = 'the'
token = 'time'
token = 'for'
token = 'all'
token = 'good'
token = 'men'
token = 'to'
token = 'come'
token = 'to'
token = 'the'
token = 'aid'
token = 'of'
token = 'their'
token = 'country'
nowisthetimeforallgoodmentocometotheaidoftheircountry

There are several problems here:

  1. Missing intitializations fro resultOrig and firstOrig (as codaddict pointed out).

  2. first = &firstOrig doesn't do what you want from it. You later do first = strtok(str, delims), which sets first to point to somewhere in str. It doesn't read data into firstOrig.

  3. You allocate small buffers (just 20 bytes) and try to fill them with much more than this. It would overflow the stack. causing nasty bugs.

You've not initialized the following two strings:

char resultOrig[20];
char firstOrig[20];

and you are appending characters to them. Change them to:

char resultOrig[20] = "";
char firstOrig[20] = "";

Also the name of the character array gives its starting address. So

result = &resultOrig;
first = &firstOrig;

should be:

result = resultOrig;
first = firstOrig;

Change

mystrcat(resultOrig, firstOrig);

to

mystrcat(resultOrig, first);

also make resultOrig to be large enough to hold the concatenations, like:

char resultOrig[100] = "";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!