0

I wrote a function that will take a char* representing a binary number, and add one to that number. I've encountered a very confusing error, which is that the function works fine and dandy when the char* comes from user input when calling the function (a.k.a. argv[1]), but gives me a Bus error: 10 when I instead initialize the variable internally and pass it to the same function. I'm not sure what's behind this, so I turn to you guys. Here's my code:

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

void addOneBinaryMain(char* strBiNum, int index)
{
    if (strBiNum[index] == '0' || index == 0) { //BUS ERROR OCCURS HERE
        strBiNum[index] = '1';
        return;
    } else {
        strBiNum[index] = '0';
        addOneBinaryMain(strBiNum, index - 1);
    }
}

void addOneBinary(char* strBiNum)
{
    addOneBinaryMain(strBiNum, strlen(strBiNum)-1);
}

int main(int argc, char* argv[]) {
    char* str = argv[1];
    char* strZero = "00000000";
    int i;

    printf("%s\n", str);
    printf("%s\n", strZero);

    addOneBinary(str);
    printf("added one to input string: %s\n", str); //succeeds
    addOneBinary(strZero);
    printf("added one to internal zero string: %s\n", strZero);

    return 0;
}

Following around the error with print statements, it seems that it occurs in the addOneBinaryMain function (the recursive step), at the point I've marked.

4

2 回答 2

1

strZero指向一个不能改变的常量字符串

于 2012-10-12T00:27:54.090 回答
1

strZero 只是用您的文字字符串“000000”的地址初始化的一个点。这个文字字符串存储在应用程序内存中只读的位置(如果我没记错的话,认为它被称为静态存储)。

尝试在堆栈或堆上声明一个 char 数组并使用 strcpy 将 strZero 复制到它。

于 2012-10-12T00:30:45.423 回答