反向字符串是段错误 [英] reverse a string is seg faulting

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

问题描述

我写了一个反向字符串"练习,为即将进行的面试做准备,但是,当我尝试对阵列中的多个项目进行测试时,我遇到了段错误.

I've written a "reverse string" exercise as a preparation for my upcoming interviews, however, when I try to run the test on several items of my array, I am getting a segfault.

基本上,如果我用-DWORKS编译下面的代码,则字符串"zip it虾"的cstr会按预期反转.但是,如果我离开了,它将编译使用指针数组但在第一次迭代时失败的代码(即cstr [i],其中i = 0):

Basically if I compile the code below with -DWORKS, cstr with the string "zip it shrimp" is reversed as expected. However, if I leave it will compile the code that uses the array of pointers but fails on the first iteration (i.e cstr[i] where i = 0):

*s = *e;

我似乎记得我们不能直接更改指针,但是我似乎想不出解决此问题的方法.我们将不胜感激,帮助您理解究竟是什么导致了故障,以及如何解决并更好地理解这一点,因此我不再赘述.完整的代码如下.

I seem to recall that we can't change a pointer directly, but I can't seem to think of a way to work around this. Any help understanding what exactly is leading to the fault and how I can fix it and understand this better so I don't repeat it again, would be greatly appreciated. Whole code below.

#include <stdio.h>

char *str[] = { "zip it shrimp", "", "a", "ab", "abc" };
char cstr[] = "zip it shrimp";

void reverse(char *str)
{       
        char *s = str;
        char *e = s + strlen(s) - 1;

        while (s < e) {
                char c = *s;
                *s = *e;
                *e = c;
                s++;
                e--;
        }
}

int main(int argc, char **argv)
{
        int i;
#ifdef WORKS
        reverse(&cstr);
        printf("%s\n", cstr);
#else
        for (i = 0; i < 4; i++) {
                reverse(str[i]);
                printf("%s\n", str[i]);
        }
#endif
        return 0; 
}       

推荐答案

反转指针数组时,您正在修改字符串文字,即未定义的行为.您不能修改以下任何字符串:

When reverse the array of pointers, you are modifying the string literals, which is undefined behaviour. You can't modify any of strings in:

char *str[] = { "zip it shrimp", "", "a", "ab", "abc" };

将字符串复制到可修改的存储位置,然后反转它们.一种方法是使用strdup().

Copy the strings into a modifiable memory locations and then reverse them. One way is to use strdup().

  for (i = 0; i < 4; i++) { 
            char *p=strdup(str[i]);
            if (!p) { /* handle error */ }
            reverse(p);
            printf("%s\n", p);
            free(p);
    }

如果只想反向打印它们,则可以打印而根本不进行任何复印.但这取决于您要如何实现.

If you simply want to print them in reverse, you can print them without doing any copy at all. But that depends on how you want implement it.

这篇关于反向字符串是段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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