为什么首先要在strcat()之前先使用strcpy()? [英] Why do i first have to strcpy() before strcat()?

查看:110
本文介绍了为什么首先要在strcat()之前先使用strcpy()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码会产生运行时问题:

Why does this code produce runtime issues:

char stuff[100];
strcat(stuff,"hi ");
strcat(stuff,"there");

但这不是吗?

char stuff[100];
strcpy(stuff,"hi ");
strcat(stuff,"there");


推荐答案

strcat 将查找null终止符,将其解释为字符串的结尾,然后在其中附加新文本,覆盖过程中的null终止符,并在连接末尾编写新的null终止符。

strcat will look for the null-terminator, interpret that as the end of the string, and append the new text there, overwriting the null-terminator in the process, and writing a new null-terminator at the end of the concatenation.

char stuff[100];  // 'stuff' is uninitialized

空终止符在哪里? 东西未初始化,因此它可能以NUL开头,或者其中可能没有NUL。

Where is the null terminator? stuff is uninitialized, so it might start with NUL, or it might not have NUL anywhere within it.

在C ++,您可以执行以下操作:

In C++, you can do this:

char stuff[100] = {};  // 'stuff' is initialized to all zeroes

现在您可以执行strcat了,因为'stuff'是空终止符,因此它将附加到正确的位置。

Now you can do strcat, because the first character of 'stuff' is the null-terminator, so it will append to the right place.

在C语言中,您仍然需要初始化 stuff,这可以通过几种方法:

In C, you still need to initialize 'stuff', which can be done a couple of ways:

char stuff[100]; // not initialized
stuff[0] = '\0'; // first character is now the null terminator,
                 // so 'stuff' is effectively ""
strcpy(stuff, "hi ");  // this initializes 'stuff' if it's not already.

这篇关于为什么首先要在strcat()之前先使用strcpy()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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