在我的代码中出现分段错误

时间:2014-02-13 01:50:25

标签: c

我的代码给了我一个分段错误。我99%肯定这个错误源于我糟糕的代码构造。

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

int decToBit(unsigned int I, char *str){

        str = "";
        int currentVal = I;

        do{
                if(I%2 == 0)
                        strcat(str,"0");
                else
                        strcat(str,"1");

                 } while(currentVal > 0);

        return(0);
}

4 个答案:

答案 0 :(得分:2)

您需要确保str中有足够的空间来添加额外的字符:

char myStr[200];
myStr[0] = '\0';  // make sure you start with a "zero length" string.
strcpy(myStr, str);

然后使用myStr使用str

原样,声明

str="";

str指向const char* - 这是一个你可以阅读但不能写的字符串。

顺便提一下,main的呼叫签名是

int main(int argc, char *argv[])
换句话说,你需要一个指向char的指针。如果我没有记错的话,你想做以下事情(这里有点介意):

每个奇怪的参数都会增加一个;每个偶数参数都会添加0。

如果我的阅读技巧有效,那么你可能想尝试一下:

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

int main(int argc, char * argv[]) {
  char temp[200];
  temp[0] = '\0';
  int ii;

  for(ii = 0; ii < argc; ii++) {
    strncpy(temp, argv[ii], 200); // safe copy
    if(ii%2==0) {
      strcat(temp, "0");
    }
    else {
      strcat(temp, "1");
    }
    printf("%s\n", temp);
  }
}

编辑刚刚意识到您编辑了问题,现在您的目的更加清晰。

稍微修改了你的功能:

int decToBit(unsigned int I, char *str){

  str[0] = '\0';
  char *digit;
  do
  {
    digit = "1";
    if ( I%2  == 0) digit = "0";
    strcat(str, digit);
    I>>=1;
  } while (I != 0);

  return(0);
}

似乎有效......

答案 1 :(得分:1)

在do-while循环中,你应该增加currentVal的值。否则它将是一个无限循环,你最终会出现分段错误。

答案 2 :(得分:1)

正确初始化str[0] 每个循环除以I 2。

但是字符串将以小尾数顺序排列。怀疑是有意的吗?

int decToBit(unsigned int I, char *str) {
  str[0] = '\0';
  do {
    if (I%2 == 0)
      strcat(str,"0");
    else
      strcat(str,"1");
    I /= 2;
  } while(I > 0);
  return(0);
}

// call example
char buf[sizeof(unsigned)*CHAR_BIT + 1];
decToBit(1234567u, buf);

答案 3 :(得分:0)

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

char *decToBit(unsigned int I, char *str){
    int bit_size = CHAR_BIT * sizeof(I);
    str += bit_size;
    *str = 0;
    do{
        *--str = "01"[I & 1];
    }while(I>>=1);
    return str;
}

int main(){
    char bits[33];
    printf("%s\n", decToBit(0, bits));
    printf("%s\n", decToBit(-1, bits));
    printf("%s\n", decToBit(5, bits));
    return 0;
}