问题描述
这是我正在尝试的代码,其中的字符串由其偶数位置字符重新定位。假设string是abcde,代码应该给出输出acebd。我还没有实现奇怪的位置strinng替换。
我的代码所做的是它连续存储偶数位置字符,当它完成时,它存储a来填充数组。这个代码所期望的输出是aceaa。但它在str [j] = str [i]行给出了分段错误。
请帮帮我。
This is a code i am trying in which string is repalced by its even position character . Let say if string is "abcde" the code should give output "acebd". I haven't implemented the odd position strinng replacement.
What my code do is it stores the even position character continously and when it is done ,it stores "a" to fill the array . I.e output expected by this code is "aceaa" . But it gives segmentation fault at line "str[j]=str[i]" .
Please do help me .
#include<stdio.h>
#include<string.h>
void moveplace(char *str)
{
int len=strlen(str);
int i=0,j=0;
while(str[i]!='\0')
{
str[j]=str[i];
i=i+2;
j++;
}
while(j<len)
{
str[j]="a";
j++;
}
}
int main()
{
int i;
char *str="abcde";
moveplace(str);
for(i=0;strlen(str);i++)
{
printf("%c ",str[i]);
}
}
推荐答案
while(str[i]!='\0')
{
str[j]=str[i];
i=i+2;
j++;
}
通过以2为步长递增 i
,您将在null上运行终结者。这可能会让你产生分段错误。
By incrementing i
in steps of 2 you will run over the null terminator at the end. And that probably produces you segmentation fault.
while(j<len)>
{
str[j]="a";
j++;
}
你的意思是
You certainly meant
str[j] = 'a';
还有第三个:
And there is a third one:
for(i=0;strlen(str);i++)
此循环运行永远。
This loop runs forever.
#include<stdio.h>
#include<string.h>
void moveplace(char * str)
{
int len = strlen(str);
int lim = len / 2 + len % 2;
int i;
for (i=0; i<lim; ++i)
{
char k = str[i];
str[i] = str[i*2];
str[i*2] = k;
}
}
int main()
{
int i;
char str[]="abcde";
moveplace(str);
for(i=0; str[i] != '\0' ;++i)
printf("%c ",str[i]);
printf("\n");
}
这篇关于代码中的分段错误替换字符串的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!