Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
%在C中,我的返回值不能正常工作_C - Fatal编程技术网

%在C中,我的返回值不能正常工作

%在C中,我的返回值不能正常工作,c,C,正如标题所说的%s工作不正常,这是针对代码战的,因此%s需要能够与阵列一起工作才能通过示例测试用例;无法更改playPass的函数声明。使用Ascii表。在main()中打印的for循环也可以工作,并提供正确的输出 #include <stdio.h> #include <string.h> #include <stdlib.h> // takes a string and shifts letter n value; // lower cases eve

正如标题所说的%s工作不正常,这是针对代码战的,因此%s需要能够与阵列一起工作才能通过示例测试用例;无法更改playPass的函数声明。使用Ascii表。在main()中打印的for循环也可以工作,并提供正确的输出

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

// takes a string and shifts letter n value;
// lower cases every other element if it contains a letter
// replaces number with a 9 complement 
// returns array with values reversed.
char* playPass(char* s, int n) 
{
    int length = strlen(s); 
    char *pass= (char *)malloc(length*sizeof(char)+1); 
    char a; 
    int letter, i; 


    for(i=0; i< length; i++) 
    {
        a = s[i];
        letter = a;

        if( letter >= 65 && letter <=90  )
        {

             letter +=n; 

            if(letter >90)
            { 
                letter -=90; 
                letter +=64; 
            } 
            if((i+1) % 2 == 0  )
            {
                letter += 32;

            }

            a = letter; 

       }
        else if(letter >= 48 &&  letter <= 57)
        {
            letter -= 48;
            letter = 9 - letter; 
            a = letter + '0'; 
        }

        pass[length - i] = a;  
   }

  return pass;   
}
// answer should be 
int main (){

    char* s ={"I LOVE YOU!!!"}; 
    int length = strlen(s);
    int k = 1; 
    s =playPass( s,k ); 
    int i; 
    printf(" %s", s);
    for(i = 0; i <= length; i++)
    { 
        printf(" %c", s[i]);
    }

}
#包括
#包括
#包括
//获取字符串并将字母n值移位;
//如果包含字母,则每隔一个元素使用小写字母
//将数字替换为9的补码
//返回值已反转的数组。
char*playPass(char*s,int-n)
{
整数长度=strlen(s);
char*pass=(char*)malloc(长度*sizeof(char)+1);
字符a;
int字母,i;
对于(i=0;i=65和字母90)
{ 
字母-=90;
字母+=64;
} 
如果((i+1)%2==0)
{
字母+=32;
}
a=字母;
}

else if(letter>=48&&letter
%s
仅适用于以null结尾的
char*

char* playPass(char* s, int n) {

    …
    for() {
       …
    }
    pass[i] = '\0'; //Null terminate here.
    return pass;
}
所以我想出来了

我将新值分配给新数组的结尾

 pass[length - i] = a;  
使其到达从未向第一个元素写入值的位置,因此

pass[0]= NULL;
必须把它改成

pass[length - (i-1)] = a; 

感谢大家的帮助,我还清理了magic numbers Great tip@phuclv!中的代码。

永远不要使用像
letter>=65&&letter
malloc()
这样的魔法数字,因为它不会对分配的内存进行零初始化,而
playPass()
函数不会给字符串一个nul(零)如果不存在nul终止符,则终止符和
%s
格式会给出未定义的行为。感谢在我修复第0个元素的空值的主要问题后的快速回复,这肯定是下一个修复。