简体   繁体   English

C连接字符串不起作用

[英]C concatenating strings won't work

int main(int argc, char** argv) {
    char data[1024];
    data[0] = '\0';
    for(int i = 1; i < argc; i++){
        strcpy(data+strlen(data), (argv[i] + 1));
    }
    strcpy(data+strlen(data), data+strlen(data)/2);
    printf(data);

    return 0;
}

As you can see this is my code so far. 如您所见,这是到目前为止的代码。 What I'm trying to do is: Remove first letter from every argument, concat them into data and after the loop take half of the resulting string and concat it again, then print it. 我想做的是:从每个参数中删除第一个字母,将它们合并为data ,然后在循环后取一半结果字符串,然后再次合并,然后打印出来。 Example: 例:

Calling the program with the arguments hello , world and yes should print: elloorldesrldes 使用参数helloworldyes调用程序应打印:elloorldesrldes

it works until strcpy(data+strlen(data), data+strlen(data)/2); 它一直工作到strcpy(data+strlen(data), data+strlen(data)/2); . Here I try to take half of the string ( data ) and concat it to the end of the same string. 在这里,我尝试取字符串( data )的一半并将其连接到同一字符串的末尾。 When I leave that part out I get the result elloorldes but when I put it in, instead of giving me the expected results I get the error RUN FAILED (exit value -1.073.741.819, total time: 4s) , however I'm not sure why that's the case. 当我省略该部分时,我得到的结果是elloorldes但是当我放入它时,没有给出预期的结果,而是得到了RUN FAILED (exit value -1.073.741.819, total time: 4s)错误RUN FAILED (exit value -1.073.741.819, total time: 4s) ,但是我没有确定为什么会这样。

You cannot do this 你不可以做这个

strcpy(data+strlen(data), data+strlen(data)/2);

because strcpy cannot handle cases when memory overlaps. 因为strcpy无法处理内存重叠的情况。

man strcpy 人strcpy

 char *strcpy(char *dest, const char *src); 

DESCRIPTION 描述

The strcpy() function copies the string pointed to by src , including the terminating null byte ( '\\0' ), to the buffer pointed to by dest . strcpy()函数将src指向的字符串(包括终止的空字节( '\\0'strcpy()复制到dest指向的缓冲区。 The strings may not overlap , and the destination string dest must be large enough to receive the copy. 字符串不能重叠 ,并且目标字符串dest必须足够大才能接收副本。

You need to use memmove for this, which handles memory overlap: 您需要为此使用memmove ,它可以处理内存重叠:

size_t oldsize = strlen(data);
size_t size = oldsize/2;

memmove(data+oldsize, data+size, size);
data[oldsize + size] = 0;

Also don't do printf(data) with content provided by the user. 也不要对用户提供的内容进行printf(data)处理。 Let's say the passed arguments are hello , world%d , then data will contain %d and printf would yield undefined behaviour, because there are arguments missing. 假设传递的参数是helloworld%d ,那么data将包含%dprintf将产生未定义的行为,因为缺少参数。

You should do this: 你应该做这个:

printf("%s\n", data);

or 要么

puts(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM