为了找到子在给定的文本。C PROGRAMM [英] To find the substring in a given text.. C programm

查看:132
本文介绍了为了找到子在给定的文本。C PROGRAMM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char *substring(char *text, int position, int length)
{
   int i, j=0;
   char *temp ;

   for(i=position-1; i<position+length-1; i++)
   {
     temp[j++] = text[i];
   }
   temp[j] = '\0';

   return temp;
}

嗨什么是在以下code中的错误..我想在Fedora机上运行的..而它给我一个运行时错误分段故障。这是什么错误一回事..和为什么它给这个错误。

Hi What is the error in the following code.. I am trying to run this on Fedora Machine.. And its giving me a run-time error "Segmentation Fault". What is this error all about.. and why is it giving this error..

谢谢..

推荐答案

您需要为温度分配内存 - 目前它只是一个悬空指针。您可以使用的malloc 此,但请注意,来电者将需要确保这个存储随后免费 D。

You need to allocate memory for temp - currently it's just a dangling pointer. You can use malloc for this but note that the caller will need to ensure that this storage is subsequently freed.

例如:

char *substring(const char *text, int position, int length)
{
   char *temp = malloc(length + 1);
   int i, j;

   for (i = position, j = 0; i < position + length; i++, j++)
   {
       temp[j] = text[i];
   }
   temp[j] = '\0';

   return temp;
}

这篇关于为了找到子在给定的文本。C PROGRAMM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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