Advertisement

C Help please

Started by February 23, 2003 11:16 AM
13 comments, last by skrovi 21 years, 8 months ago
add: #include <stdlib.h>

Beginner in Game Development?  Read here. And read here.

 

quote: Original post by skrovi
char *hex = (char *)malloc(sizeof(100));

You can''t allocate the "size of 100"! The size of 100 what? 100 8 bit chars? In that case you have to allocate the size of a char multiplied by how many chars you want. For instance:

  char* hex = (char*)malloc(sizeof(char)*100);//or to clear all index values to 0:char* hex = (char*)calloc(100, sizeof(char));//and here''s an error checking function:template<class Datatype> //this makes allocation of types genericbool alloc(Datatype* hex, int p_size){   hex = (Datatype*)calloc(size, sizeof(Datatype));   hex == NULL ? return true : return false;}//for which you would call this:char* hex;if(alloc(&hex, 100)){    //error handling }  
This post will self-destruct in 5 seconds...Actually, it's just Benjamin Bunny doing his thing.
Advertisement
nice code.
but you''re a little late aren''t you?
i''m referring to:
quote:
You can''t allocate the "size of 100"! The size of 100 what? 100 8 bit chars? In that case you have to allocate the size of a char multiplied by how many chars you want.


anyway i and some others already discussed that point.
also since he''s doing this in straight C (he does mention this a few posts above), the template you gave would not be suitable. maybe va_arg/va_macro solution would do?

Beginner in Game Development?  Read here. And read here.

 

ok, just to clear up the confusion, this is the latest and the greatest code that I could come up with someof ur help included..if any one can think of a better solution let me know...
"Converst hex into Decimal"


#include <stdio.h>
#include <cmath>
#include <stdlib.h>

int Hex2Base10(const char* pHex)
{
int base10 = 0;
int exponent = 0;
const char* pChar = pHex;
while (*pChar != ''\0'')
{
exponent++;
pChar++;
}
pChar = pHex;
while (*pChar)
{
int digit;
if ((*pChar >= ''0'') && (*pChar <= ''9''))
digit = *pChar - ''0'';
else if ((*pChar >= ''A'') && (*pChar <= ''F''))
digit = 10 + *pChar - ''A'';
else if ((*pChar >= ''a'') && (*pChar <= ''f''))
digit = 10 + *pChar - ''a'';
else
return -1; // error!
base10 += (int)(digit * pow(16, --exponent));
pChar++;
}
return base10;
}

int main ()
{
int valBase10 = 0;
char *hex = (char *)calloc(100, sizeof(char));
printf ("Enter the Hex Digit: ");
gets(hex);
printf("The value of %s in Decimal is %i\n", hex, Hex2Base10(hex));
if (hex != NULL)
free(hex);
return 0;
}
quote: Original post by Alpha_ProgDes
maybe va_arg/va_macro solution would do?

What did you say?
This post will self-destruct in 5 seconds...Actually, it's just Benjamin Bunny doing his thing.

This topic is closed to new replies.

Advertisement