我可以在一个空字符串复制字符串? [英] Can I copy a string in an empty string?

查看:311
本文介绍了我可以在一个空字符串复制字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假如我不喜欢这样复制的字符串。

Suppose I do like this to copy the string.

char str[] = "";
char *str2 = "abc";
strcpy(str, str2);
printf("%s", str);  // "abc"
printf("%d", strlen(str));  // 3

那么,为什么不给我不确定的行为或造成程序失败。什么是做这样的缺点是什么?

Then, why it doesn't give me undefined behaviour or causing the program to fail. What are the disadvantages of doing like that ?

推荐答案

这code绝对是导致栈的问题,但这样的小弦,你是不是看到的问题。举个例子,执行下列操作:

This code is definitely causing a stack problem, though with such a small string, you are not seeing the issue. Take, for example, the following:

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

int main()
{
        char str[] = "";
        char *str2 = "A really, really, really, really, really, really loooooooooooooooonnnnnnnnnnnnnnnnng string.";
        strcpy(str, str2);
        printf("%s\n", str);
        printf("%d\n", strlen(str));
        return 0;
}

有一个人为的例子,是的,但运行此的结果是:

A contrived example, yes, but the result of running this is:

A really, really, really, really, really, really loooooooooooooooonnnnnnnnnnnnnnnnng string.
92
Segmentation fault

这也是为什么strcpy函数气馁的原因之一,并拷贝使用和串接需要指定有关串的大小的功能,建议。

This is one of the reasons why the strcpy function is discouraged, and usage of copy and concatenate functions that require specifying the sizes of the strings involved are recommended.

这篇关于我可以在一个空字符串复制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆