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.

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

commented: right :) +36

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.