倒装词。(以null结尾的c字符串字符数组)。为什么不是';这不管用吗
我正在尝试反转字符数组并使用%s打印它。但它不起作用。我没有得到任何印刷品。为什么呢?我的代码很简单/倒装词。(以null结尾的c字符串字符数组)。为什么不是';这不管用吗,c,c-strings,C,C Strings,我正在尝试反转字符数组并使用%s打印它。但它不起作用。我没有得到任何印刷品。为什么呢?我的代码很简单/ char* reverse(char* word){ int i = 0; int length=0; while (word[i] != '\0'){ i++; } length = i; char* temp_word = malloc(len
char* reverse(char* word){
int i = 0;
int length=0;
while (word[i] != '\0'){
i++;
}
length = i;
char* temp_word = malloc(length* sizeof(char));
for (i = 0; i < length; i++){
temp_word[i] = word[length - i];
word[i] = temp_word[i];
}
return word ;
}
char*反向(char*字){
int i=0;
整数长度=0;
while(单词[i]!='\0'){
i++;
}
长度=i;
char*temp_word=malloc(长度*sizeof(char));
对于(i=0;i
应该是
temp_word[i] = word[length - i - 1];
如果
word[]
的长度为3个字符,则word[3]
实际上是空终止符。这是有效的。。。您没有为空终止符分配空间。。。您正在通过这样的“word[i]=temp_word[i]”进行覆盖
#include <stdio.h>
#include <stdlib.h>
char *reverse(char *);
int main()
{
char sWord[10] = "PHONE";
char *temp = NULL;
printf("Before reverse() => %s\n", sWord);
temp = reverse(sWord);
printf("After reverse() => %s\n", temp);
return 0;
}
char *reverse(char *word)
{
int i = 0;
int length = 0;
while(word[i] != '\0')
{
i++;
}
length = i;
char *temp_word = malloc(length * (sizeof(char)+1)); // +1 here.
for (i = 0; i < length; i++)
{
temp_word[i] = word[length - (i+1)];
//word[i] = temp_word[i]; <== Do not need this.
}
temp_word[length] = '\0';
return temp_word ;
}
#包括
#包括
字符*反向(字符*);
int main()
{
字符剑[10]=“电话”;
char*temp=NULL;
printf(“反转前()=>%s\n”,剑);
温度=反向(剑);
printf(“在reverse()之后=>%s\n”,temp);
返回0;
}
字符*反向(字符*字)
{
int i=0;
整数长度=0;
while(单词[i]!='\0')
{
i++;
}
长度=i;
char*temp_word=malloc(长度*(sizeof(char)+1));//+1。
对于(i=0;i //word[i]=temp_word[i];提示:(与代码不工作无关):您可以就地反转…使用库字符串。h。但我正在尝试在没有库的情况下执行此操作否。不使用库!!!!就地意味着没有任何内存分配…哦,是的,我知道临时数组。我首先执行此操作,但它不起作用,所以我执行了此操作。不知道为什么要使用相同的概念。但它不起作用。我们可以关注此特定错误吗?为什么你们总是转向其他问题,所以用第二个问题覆盖字符串的前半部分。第一个问题随后会丢失。即使进行了此更改,代码仍然无法工作,因为它会用第二个问题覆盖字符串的前半部分,然后将其复制回后半部分,例如,brick变为kcick
#include <stdio.h>
#include <stdlib.h>
char *reverse(char *);
int main()
{
char sWord[10] = "PHONE";
char *temp = NULL;
printf("Before reverse() => %s\n", sWord);
temp = reverse(sWord);
printf("After reverse() => %s\n", temp);
return 0;
}
char *reverse(char *word)
{
int i = 0;
int length = 0;
while(word[i] != '\0')
{
i++;
}
length = i;
char *temp_word = malloc(length * (sizeof(char)+1)); // +1 here.
for (i = 0; i < length; i++)
{
temp_word[i] = word[length - (i+1)];
//word[i] = temp_word[i]; <== Do not need this.
}
temp_word[length] = '\0';
return temp_word ;
}