为什么这个节目给分割的错吗? [英] Why does this program give segmentation fault?

查看:116
本文介绍了为什么这个节目给分割的错吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个初学者的问题:为什么这个破/给人一种错误?

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&string.h中GT;字符* strtrim_right(字符* P)
{
  字符*结束;
  INT LEN;
  LEN = strlen的(对);
  而(* P&放大器;&放大器; LEN)
    {
    最终= P + LEN-1;
    如果(因而isalpha(*结束))
     *结束= 0;
   其他
    打破;
    }
  返回(P);
}
诠释的main()
{
  字符* X =PM123BFD;
  strtrim_right(X);
  的printf(%S,X);
  返回0;
}


解决方案

修改

 的char * x =PM123BFD;

 字符X [] =PM123BFD;

您不能修改字符串常量,所以不是传递函数字符阵列,它可以修改。

It's a beginners question: Why is this breaking/giving an error?

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

char *strtrim_right(char *p)
{
  char *end;
  int len;
  len = strlen( p);
  while (*p && len)
    {
    end = p + len-1;
    if(isalpha(*end))
     *end =0;
   else 
    break;      
    }
  return(p);
}


int main ()  
{  
  char *x="PM123BFD";
  strtrim_right(x);
  printf("%s", x);
  return 0;
}  

解决方案

Change

char *x="PM123BFD";

to

char x[]="PM123BFD";

You cannot modify a string literal, so instead pass the function a char array which it can modify.

这篇关于为什么这个节目给分割的错吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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