【发布时间】:2015-07-17 04:36:30
【问题描述】:
在离开了几年之后,我又恢复了 C 编码的乐趣。
我给自己做了一个练习,使用fgets() 将文本从标准输入安全地复制到字符串,然后复制到一个字符串足够大,即只有足够的容量来容纳数字。我实际输入的字符数,最终是为了从头开始制作列表、堆栈等,换句话说,就是玩指针。
我在控制流的后期为strcpy() 定义目标字符串变量时,唯一的方法是管理这种kludge 的味道。有没有更优雅/更动态的方式来做到这一点?
#inlcude <stdio.h>
#include <string.h>
#define MAXLENGTH 20
int main(int argc, char *argv[]) {
char message[MAXLENGTH];
printf("Enter a string: \n");
fgets(message, MAXLENGTH, stdin);
/* various tests here, omitted for brevity */
char destinationString[strlen(message)];
/*
* Just testing to prove that
* the strlen() of the destination
* string is LESS than MAXLENGTH
*/
printf("Here's the strlen() of destinationString: %lu\n", strlen(destinationString));
printf("Here's the sizeof() destinationString: %lu,\n" sizeof(destinationString));
printf("Here's the contents of the copy: %s", destinationString);
return 0;
}
【问题讨论】:
-
您可能在
destinationString中有缓冲区溢出(我假设您在printf语句之前的某处有一个str[n]cpy)。您需要一个额外的字符来存储最后一个终止字符。 -
@tangrs:我同意,尽管如果代码检查换行符并消除它可能没问题。但是,如果行长于 18 个字符(不是很长),则缓冲区中不会有换行符,则可能会发生溢出。
-
自从我用 C 编写代码以来已经有一段时间了。在早期的 C 版本中,您只能在函数的开头声明变量。您的方法对我来说看起来很实用,并且在使用变量之前声明一个变量会缩小该变量的范围,IMO 这是一件好事。
-
destinationString 是一个可变长度数组,VLA,它几乎肯定不适合您的需求。
-
在类 UNIX 系统上,函数
strdup()用于此类任务。