0

I wrote this small program for a class im taking, and its supposed to take an int n and a radix (int between 2 and 16) r and give me the number converted to the new base. It only has to go from decimal to other radix's. I run my program and put in the input but for some reason im getting a segmentation fault. I know this means I most likely have a memory allocation issue but i don't know where, why, or how to find it. Can someone please show me where I went wrong?

/*Adam Ross Cohen -- 000891451 -- CSI333 Fall 09 Program 1a*/
#include <stdio.h>

int main(void)
{
  int n, r, i, count, temp;
  count = 0;
  char hex[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
  char ans[40];
  printf("Enter two integers (the ladder between 2 and 16): ");
  scanf("%d",&n);
  printf("you entered %d \n",n);
  scanf("%d",&r);
  printf("You entered %d \n",r);
  temp = n;
  while(n != 0)
    {
      temp = n % r;
      ans[count] = hex[temp];
      count++;
    }
  for(i = 39; i > 0; i--)
    {
      printf("%c", ans[i]);
    }
  return 0;
}

thanks ahead of time for any help.

Edited by splurchner: n/a

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by splurchner
1

pls reconsider your while loop. its a infinite loop. 'n' never changes so 'count' gets continuous increment. hence 'ans[count]' gives segfault.

Votes + Comments
right :)
0

thanks, that was really foolish of me, probably would have never noticed it on my own though.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.