0

I'm trying to get work this program but I'm failing. I don't know where I'm wrong. I get segmentation fault. It's probably the error is due to a pointer that doesn't work.

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

void ConvertBin(int n, int *ris,int *bit);

int main(int argc, char *argv[]) 
{
    int n;
    int ris[20];
    int bit;

    printf("Insert num: "); scanf("%d", &n);

    ConvertBin(n,ris,&bit);

    for (int i=bit; i!=0; i--) 
    {
        printf("%d", *(ris+i));
    }   

    return 0;
}

void ConvertBin(int n, int *ris, int *bit)
{
    int i = 0;

    while (n!=0)
    {
        *(ris+i) = n%2;
        n = n/2;
        i++;
    }

    bit = &i;
}
4

2 回答 2

2

错误在函数的最后一行。bit = &i;设置bit为局部变量的地址i(从函数返回后变量不再存在)。之后没有使用value of bit,实际上函数的最后一行根本没有任何作用。并且调用函数 ( main) 没有收到其bit变量的更新值。

您需要改写*bit = i;:这会将值写入i到变量指针 by bit(在您mainbit情况下)。

于 2013-11-09T21:40:58.870 回答
-1

问题出在变量 i 上,它比应有的大一点。这应该可以正常工作:

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

void ConvertBin(int n, int *ris,int *bit);

int main(int argc, char *argv[]) 
{
    int n;
    int ris[20];
    int bit;

    printf("Insert num: "); scanf("%d", &n);

    ConvertBin(n,ris,&bit);

    for (int i=bit; i>=0; i--) 
    {
        printf("%d", *(ris+i));
    }   

    return 0;
}

void ConvertBin(int n, int *ris, int *bit)
{
    int i = 0;

    if( !n ){
        *(ris) = 0;
        i++;
    } else{
        i = 0;
        do
        {
            *(ris+i) = n%2;
            n = n/2;
            i++;
        } while (n!=0);
    }
    *bit = i -1;
}
于 2013-11-09T22:22:52.767 回答