为什么此C代码遇到总线错误? (不允许使用外部功能) [英] Why is this C code getting a bus error? (No external functions allowed)

查看:78
本文介绍了为什么此C代码遇到总线错误? (不允许使用外部功能)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用了几个小时的代码,但是找不到错误.它通过了编译器,但是在运行时却遇到了总线错误,为什么?

I've been working through this code for hours but couldn't locate the error. It passes the compiler, but while running it gets a bus error, why?

char    *ft_strrev(char *str);

char    *ft_strrev(char *str)
{
    int i;
    int count;
    int d;
    char temp[5];

    i = 0;
    count = 0;
    d = 0;
    while (str[count] != '\0')
    {
        count++;
    }
    while (d < count)
    {
        temp[d] = str[d];
            d++;
    }
    while (--count >= 0)
    {
        str[i] = temp[count];
        i++;
    }
    return (str);
}

int main()
{
    char *pooch;
    pooch = "allo";
    ft_strrev(pooch);
    return (0);
}

推荐答案

您的函数正在修改字符串.在代码中,您传入文字字符串.您不应该更改文字字符串.

Your function is modifying the string. In the code you pass in a literal string. You should not change literal strings.

请改为使用以下内容:

char pooch[5];
pooch[0] = 'a';
pooch[1] = 'l';
pooch[2] = 'l';
pooch[3] = 'o';
pooch[4] = 0;
ft_strrev(pooch);
return 0;

这篇关于为什么此C代码遇到总线错误? (不允许使用外部功能)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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