Can someone help me to make my function getbase2 to work? It needs to return a string value.

#include<stdio.h>

char GetBase2(int iBase, int iNumber);

int main()
{
int i;
int number;

	
printf("Enter number: ");
	scanf("%i", & number);

printf("Enter base: ");
	scanf("%i", & i);
	
	
	printF("Conversion: %s\n",GetBase2(i,number));
	
}	

// Base 11 upwards conversion function
char GetBase2(int iBase, int iNumber)
{
	char iResult;
	int Result[64];
	int Index = 0;
	char BaseDigit[32] = 
	{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
		'D', 'E', 'F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V'};
	
	if (iBase>32)
		iResult = '0';
	
	//Base conversion starts
	while (iNumber != 0)
	{
		Result[Index] = iNumber % iBase;
		iNumber = iNumber / iBase;
		++Index;
	}
		
	//Back up to the last entry in the array
	--Index;
	
	//Prints backwards to get the right result
	for (;Index>=0;Index--)
		iResult = iResult + BaseDigit[Result[Index]];
	
	return iResult;
		
}

Recommended Answers

All 3 Replies

To return a string you have to pass it into the function as a pointer. The return statement cannot return a string.

Your for statement at the end will never exit. And what are you calculating in iResult?

try compiling this code and u can figure out the solution from the error.

use character pointer for return. Instead of using char iResult ..use char array and return that.

For loop should work properly.

character arrays that are created on the stack like iReturn[] can not be returned because they are destroyed as soon as the function returns.

You have two options

1) Have the calling function create the array and pass it to GetBase2() as a parameter, such as char* GetBase2(int iBase, int iNumber, char iReturn[]) . Note that the function return is char*, not just char


2: Make iReturn a pointer, allocate it with malloc(), return it like you tried to do. In this case, the calling function -- main() -- will have to free it when done with it. char *iReturn = malloc(64);

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.