简体   繁体   中英

Segmentation fault when i run my C program

I'm trying to create a function that converts a binary code to a decimal number, but every time I run this program the result is "Segmentation fault". Is there a way to solve this problem?

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

int btod2(int bin){
  char *stringNumer[10];
  sprintf(*stringNumer, "%d", bin);
  int len = strlen(*stringNumer);
  int result = 0, num;

  for(int i=0; i<9; i++){
    num = atoi(stringNumer[i]);
    if(*stringNumer[i] == '1'){
      result = result + (num*pow(2, len-i-1));
    } else if(*stringNumer[i] == '0'){
      result = result + (num*pow(2, len-i-1));
    } else{
      printf("ERROR\n");
    }
  }

  return result;
}

int main() {

  int b;
  printf("Enter the binary code: ");
  scanf("%d", &b);
  printf("%d\n", btod2(b));

  return 0;
}

There are other problems with your code, but to answer the question,

char *stringNumer[10];

creates an array of 10 pointers to chars. But since stringNumber is an array, when you do *stringNumber it is the same as stringNumber[0] , and stringNumber[0] is NULL since it was just declared. So you do sprintf(NULL, "%d", bin); which immediately seg fault.

What you wanted to do was as array of chars:

char stringNumer[10];
sprintf(stringNumer, "%d", bin);
int len = strlen(stringNumer);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM