简体   繁体   中英

strcpy is not working well with pointer array

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

int main(int argc, char *argv[])
{
    char *ptr;
    char temp[20];

    if (strlen(argv[1]) < strlen(argv[2]))
    {
        strcpy(temp,argv[1]);
        strcpy(argv[1],argv[2]);
        strcpy(argv[2],temp);
    }

    ptr = strstr(argv[1],argv[2]);
    if (ptr == NULL)
        printf("Non-inclusive");
    else
        printf("%s is part of %s", argv[2], argv[1]);
    return 0;
}

When I enter "abc abcd", I want to get "abc is part of abcd" as a result, but real result is "abc is part of abcdabc"

The length of each string in the argv array is fixed. So when you attempt to swap the contents of argv[1] and argv[2] when their sizes are different you write past the end of the shorter one. This triggers undefined behavior .

Better to use separate char * variables, one pointing the longer string and one pointer to the shorter.

int main(int argc, char *argv[])
{
    char *ptr;
    char *s_short, *s_long;

    if (strlen(argv[1]) < strlen(argv[2])) {
        s_short = argv[1];
        s_long = argv[2];
    } else {
        s_short = argv[2];
        s_long = argv[1];
    }

    ptr = strstr(s_long,s_short);
    if (ptr == NULL)
        printf("Non-inclusive");
    else
        printf("%s is part of %s", s_short, s_long);
    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