代码中的分段错误替换字符串的位置 [英] Segmentation Fault in Code which replaces string in position

查看:95
本文介绍了代码中的分段错误替换字符串的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在尝试的代码,其中的字符串由其偶数位置字符重新定位。假设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]);
    }
}

推荐答案

您的代码中有几个错误。

There are several bugs in your code.
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.


可能还有其他问题,但您的第一个循环有缺陷。检查当前索引位置是否为'\0'(精细)但是将i递增2.因此,如果NULL位于任何奇数位置(1,3,5,7 ...),您的索引将跳过它过了字符串的结尾。您传递的字符串有6个字符,索引为5时为NULL。
There may be other problems, but your first loop is defective. You check if the current index location is '\0' (fine) but increment i by 2. So if the NULL is in any odd location (1, 3, 5, 7...), your index will skip over it past the end of the string. The string you pass has 6 characters with the NULL at index 5.


以下代码应满足您的要求:

The following code should satisfy your requirements:
#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");
}


这篇关于代码中的分段错误替换字符串的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆