如何保护动态char不被第二个动态char覆盖?

#include  #include  #include  char print_two(char *reg, char *s) { int i, l_s = (int) strlen(s), l_reg = (int) strlen(reg); for(i = 0; i < l_reg; i++) { printf("\n %c \n", reg[i]); } return 0; } int main(void) { char reg; printf("Give a rule: "); scanf("%s", &reg); char s; printf("Give a string: "); scanf("%s", &s); print_two(&reg, &s); return 0; } 

程序开始:

 Give a rule: qwert Give a string: asdf result: d q a s d f 

我如何避免s覆盖reg

我尝试使用realloc,malloc – 0效果。

两个变量应该是动态的。

有可能吗?


用户给55个字符 – >数组55

用户给出100个字符 – >数组100

根据您对其他答案的评论,如果您可以使用GNU库扩展(主要在Linux或Windows MinGW上),则可以在scanf格式字符串中使用%ms ,如下所示:

 char *reg = NULL; // set to NULL to get segfault on uninitialized use printf("Give a rule: "); scanf("%ms", &reg); // scanf will malloc enough space to reg // check for null in case scanf failed to read anything for some reason // could also check return value of scanf, which is number of items it got if (reg != NULL) { // process reg } free(reg); // free(NULL) is not an error, it just does nothing reg = NULL; // set to NULL to get segfault on uninitialized use 

其他答案显示了如何使用固定大小的缓冲区,这是标准的C.虽然根据man scanf notes部分 , %ms可能是未来的POSIX标准。 GNU也有较旧的%as ,但在支持时(即在任何现代GNU系统中), %ms应该是首选。

scanf("%s", ...)正在从stdin读取一个字符串。 您的变量reg和s正在为一个字符分配存储空间,而不是为完整字符串分配存储空间。 例如,如果输入字符串最长为128个字符,则需要将其更改为char reg[128] 。 为防止缓冲区溢出,还应考虑使用scanf("%127s", ...)限制scanf扫描的输入长度。

您不能将字符串(多个字符)读入单个字符,如char s

您需要预留更多空间:

 char reg[128], s[128]; 

否则内存中的随机内容会被覆盖,并且您将获得未定义的行为。