这个C代码有什么问题? (不按预期工作)

时间:2013-03-23 15:16:18

标签: c function pointers

我为我的C课做了另一个练习。代码不会崩溃,但它不能按预期工作。显然我犯了一个我找不到的错误。 作业如下: 用户输入两个字符c1和c2以及一个整数n,你必须创建一个动态创建的函数,并返回一个包含n个字符的字符串,如下所示:c1c2c1c2c1c2等。 例如: c1 = a和c2 = s且n = 4字符串为:asas

但是我创建的数组不包含c1和c2,而是ASCII表中的一些随机字符。加上这里:

printf("\nThe string is: %s\n",s);

屏幕中的输出是这样的:Ohe string是:I(Insted of the string is:s-what s is-) 这是.exe文件中的照片链接:

enter image description here

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

char* alternate(char c1,char c2,int n)
{
    int i;
    char *s;
    s=(char*)malloc((n+1)*sizeof(char));
    if(s==NULL)
    {
        puts("Could not allocate memory!");
        exit(1);
    }
    for(i=0;i<n;i++);
    {
        if(i%2==0)
            s[i]=c1;
        else
            s[i]=c2;
    }
    s[i]='\0';
    return s;
}

main()
{
    char c1,c2,*s;
    int n;
    puts("Give two characters: ");
    scanf("%c %c",&c1,&c2);
    fflush(stdin);
    puts("Give an integer: ");
    scanf("%d",&n);
    s=alternate(c1,c2,n);
    printf("\nThe string is: %s\n",s);
    free(s);
    system("pause");
}

提前谢谢!

2 个答案:

答案 0 :(得分:6)

删除

上的;
for(i=0;i<n;i++);
{

它不属于那里。

答案 1 :(得分:5)

删除for循环语句旁边的分号:

 for(i=0;i<n;i++);

我取下了分号&amp;试过你的代码&amp;它按预期打印文本。

for循环旁边的分号使它成为一个空循环,之后的语句只是一些作用域的赋值。也就是说,

for(i=0;i<n;i++);
    {
        if(i%2==0)
            s[i]=c1;
        else
            s[i]=c2;
    } 

相同
for(i=0;i<n;i++) 
{

}

{
   if(i%2==0)
      s[i]=c1;
   else
      s[i]=c2;
 } 
相关问题