首页 文章

C.传递要修改的指针导致分段错误

提问于
浏览
1

我正在C中为类创建一个十进制到二进制转换器 . 我想将char数组传递给我的函数以及将小数作为int传递 . 即void DtoB(int decimal,char * array); DtoB将进行数学运算并将数组修改为二进制值 . 理想情况下,给它int值 . Main()将只扫描f(十进制),DtoB(十进制,数组)和printf(数组) .

这就是我所拥有的 . 这只会返回一个分段错误

1 #include <stdio.h>
2 #include <math.h>
3
4 void DecToBin(unsigned int, char *binary);
5
6 int main()
7 {
8         unsigned int dec;
9         char *binary[];
10         while(1) {
11                 scanf("%d", &dec);
12                 DecToBin(dec,*binary);
13                 printf("In binary is ");
14                 printf("%s\n",binary);
15         }
16 }
17 void DecToBin(unsigned int dec, char *binary)
18 {
19         int counter=0;
20         while(dec) {
21                 binary[counter]=dec%2;
22                 dec/=2;
23                 counter++;
24         }
25 }

我希望它像这样完成,因为这似乎是能够做32位整数的最佳方法,同时保持阵列的最小尺寸 . 抱歉,如果我杀了格式化 . 任何帮助表示赞赏 .

2 回答

  • 1
    char *binary[33]
    

    binary是指针数组 . 所以它中的每个元素都是一个指针 .

    分段错误是因为您没有初始化阵列并尝试使用它 .

    您正在取消引用未指向任何有效内存位置的指针 .

    在使用它们之前,需要为数组成员分配内存

  • 1

    包含所有注释,包含错误检查等 . 发布的代码变为:

    #include <stdio.h>
    #include <stdlib.h>  // exit(), EXIT_FAILURE
    #include <string.h>  // memset()
    
    
    // prototypes
    void DecToBin(unsigned int, char *binary);
    
    int main()
    {
            unsigned int dec;
            char binary[sizeof(int)*8 +1];
    
    
            while(1)
            {
                    if( 1 != scanf("%u", &dec) )
                    { // then scanf failed
                        perror( "scanf for decimal value failed" );
                        exit( EXIT_FAILURE );
                    }
    
                    // implied else, scanf successful
    
                    DecToBin(dec, binary);
                    printf("In binary is ");
                    printf("%s\n",binary);
            }
    }
    
    
    void DecToBin(unsigned int dec, char *binary)
    {
            size_t counter= sizeof(int)*8;
    
            memset( binary, ' ', counter );
            binary[ counter ] = '\0'; // terminate string
            counter--;
    
            // do...while allows for dec being 0
            do
            {
                    binary[counter]= (char)((dec%2)+ 0x30);
                    dec /= 2;
                    counter--;
            }  while(dec);
    }
    

    仍然存在用户留下空白屏幕和闪烁光标的缺点 . I.E.代码应该通过请求输入值来提示用户 .

相关问题