c - 避免总线错误 : 10 during test cases

标签 c

我试图在不使用任何额外缓冲区的情况下从字符串中删除重复字符。当我像这样声明单个变量时,代码有效

char s[] = "aaabbb";

但当我试图循环通过一些测试用例时不是。

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

/* Design an algorithm and write code to remove the duplicate characters in a string
without using any additional buffer. NOTE: One or two additional variables are fine.
An extra copy of the array is not. */

void removeDuplicates(char s[]) {
    // attempts to modify array in place without extra buffer
}

int main() {
    char *s[4] = {"aaaa", "abcd", "ababab", "aaabbb"};

    int i;
    for (i = 0; i < 6; i++) {
        removeDuplicates(s[i]);
    }
    return 0;
}

这会返回 Bus error: 10 因为它试图修改字符串文字 "aaaa" 但我不确定如何在保持良好设置的同时克服这个问题测试用例。

最佳答案

s[i] 指向字符串文字,您需要一个像这样的二维 char 数组:

char s[][7] = {"aaaa", "abcd", "ababab", "aaabbb"}

另请注意,对于长度为 n 的字符串,您至少需要 n+1 个空格,因为 '\0' 终止。"aaabbb"` 的长度为 6,因此至少需要 7 个空格。

然后你可以做

int main() {
    char s[][7] = {"aaaa", "abcd", "ababab", "aaabbb"};

    size_t i;
    for (i = 0; i < sizeof s / sizeof s[0]; i++) {
        removeDuplicates(s[i]);
    }
    return 0;
}

关于c - 避免总线错误 : 10 during test cases,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49591050/

相关文章:

c - 在 C 中写入大量文件后 Ubuntu 死机

c - OpenGL - 转换立方体

c - 如果 nelem 或 elsize == 零,为什么 calloc 分配 1 个字节?

函数可以在 C 中返回多个值吗?

c - foo(int arr[]) 和 foo(int arr[10]) 有什么区别?

cgtk警告: initialization makes integer from pointer

c - 在初始化函数中传递数组地址

c - 用 C 和 OpenMP 进行矩阵乘法

c - 编程换行

c++ - 防止在 printf C C++ 中打印符号