0

I was assigned to make a int to binary converter. I made one and it work as it should however when attempting to make a char pointer and print the char array the pointer is pointing to it print weird character which I am guessing is the memory location. Am I using pointer right?

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

char* tobinary(int x)
{
	char bin[8] = {'0', '0', '0', '0', '0', '0', '0', '0'};

	int num[8] = {128, 64, 32, 16, 8, 4, 2, 1};
	
	int i;
	for (i = 0; i < 8; i++)//pass
	{
		if (x >= num[i])//pass
		{
			x -= num[i];//pass
			bin[i] = '1';
		}
	}
	printf("%s", bin);//pass
	char* ptr = bin;
	printf("%s", ptr);//pass
	return ptr;	
}

void main()
{
	char input_num[256];
	printf("Enter a Integer\n");
	fgets(input_num, 256, stdin);
	input_num[strlen(input_num)-1] = '\0';

	int x = atoi(input_num);
	printf("%s", tobinary(x));
	printf("\n");
	//tobinary(x);
}

Edited by zetologos: n/a

3
Contributors
5
Replies
9
Views
6 Years
Discussion Span
Last Post by jnawrocki
0

>>printf("%s", bin);//pass

bin must be a null-terminated character array if you want to use printf() to display its contents. For example. Note that you don't have to specifiy its size, the compiler will figure that out for you from the list of initializers. char bin[] = {'0', '0', '0', '0', '0', '0', '0', '0',0};

Edited by Ancient Dragon: n/a

0

it works when inside the method:
printf("%s", bin);//print char array PASS
char* ptr = bin;

printf("%s", ptr);//print char pointer PASS
return ptr;

0

Change: char bin[8] = {'0', '0', '0', '0', '0', '0', '0', '0'};
To: static char bin[8] = {'0', '0', '0', '0', '0', '0', '0', '0'};

So that the variable hangs around after the function ends.

Edited by jnawrocki: n/a

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.