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

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

我怎样才能避免被reg覆盖s

我尝试了 realloc,malloc - 0 效果。

两个变量应该是动态的。

有可能吗?


用户给出 55 个字符 -> 数组 55

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

4

3 回答 3

3

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

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注释部分%ms可能在未来的 POSIX 标准中。GNU 也有较旧的%as,但%ms在受支持时应该首选(即在任何现代 GNU 系统中)。

于 2013-01-28T16:09:52.633 回答
2

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

于 2013-01-28T15:58:12.357 回答
0

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

您需要预留更多空间:

char reg[128], s[128];

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

于 2013-01-28T15:55:39.803 回答