给定一个字符串,编写一个程序通过替换 ? 来生成所有可能的字符串。用 0 和 1?

Given a string write a program to generate all possible strings by replacing ? with 0 and 1?

我写了这段代码,它对 a?b?c 工作正常吗?和 a?b?c?d?但是对于 a?b?c?d?e?它在最后给出了一个额外的垃圾值。在 s 的末尾附加了 '\0' 字符然后为什么以及如何读取该垃圾值。我试图通过在代码之间放置 printf 语句来调试它,但无法解决它。请帮忙

#include<stdio.h>
void print(char* s,char c[],int l)
{
    int i,j=0;
    for(i=0;s[i]!='[=10=]';i++)
    {
        if(s[i]=='?')
        {
            printf("%c",c[j]);
            j++;
        }
        else
            printf("%c",s[i]);
    }
    printf(", ");
}
void permute(char *s,char c[],int l,int index)
{
    if(index==l)
    {
        print(s,c,l);
        return;
    }
    c[index]='0';
    permute(s,c,l,index+1);
    c[index]='1';
    permute(s,c,l,index+1);
}
int main()
{
    char s[10],c[10];
    printf("Enter a string.");
    scanf("%s",s);
    int i,ct=0;
    for(i=0;s[i]!='[=10=]';i++)
    {
        if(s[i]=='?')
            ct++;
    }
    permute(s,c,ct,0);
    return 0;
}

我的输出是这样的:-

a0b0c0d0e0♣, a0b0c0d0e1♣,

...等等。

正如我们从您的代码中看到的那样,数组定义为 char s[10] 并且输入为

a?b?c?d?e?

输入要与空终止符一起保存在 s

 scanf("%s",s);

您需要使用更大的数组。否则,尝试在输入后添加终止空值时,将访问调用 undefined behaviour.

的越界内存

也就是说,绝不允许 unbound 输入到有限大小的数组,始终使用字段宽度来限制输入长度(换句话说, reserve the space for null terminator), like

 scanf("%9s",s);

此处的代码生成了正确的输出,但请注意,对于大小大于或等于 10 个字符的字符串,它具有未定义的行为,因为这是您的缓冲区的大小。

因此,对于 a?b?c?d?e?,您需要至少 11 个字符的缓冲区,以考虑空终止符。你应该把 s 变大。

实际上在 C 中看到在 String 中发生的事情是每次它最后附加一个 '[=11=]' 字符。

现在注意在 C 中没有什么叫做字符串。

它是字符数组。

所以如果你这样定义-

char s[10]

这实际上接受少于 9 个字符的数组,因为最后一个字符将是 '[=11=]' 字符。

如果你添加超过 9 个字符,它会给出错误的输出。