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);
}

>>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};

didnt change anything.

In that case your tobinary() function is just wrong. Read some of these links to see how its done.

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;

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.

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.