1. Method 1 uses a first-level pointer
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int convert (char * myp, int mylen, int * Poutput)
{
int i = 0;
char * pstart = myp + 1;
char * Pstop = myp + mylen - 1;
int ant = 0;
int hex = 1;
if(Pstop == NULL )
{
return -1;
}
if(myp == NULL)
{
return -1;
}
while(Pstop > pstart)
{
for(i = 0; i < mylen - 2; i++)
{
if(*Pstop >= 'A' && *Pstop <= 'F')
{
ant = ant + (*Pstop - 'A' + 10) * hex;
}
else
{
ant = ant + (*Pstop - '0') * hex;
}
Pstop -;
hex = hex * 16;
}
}
*Poutput = ant;
return 0;
}
intmain()
{
char buf1[10];
int output = 0;
int len = 0;
int ret = 0;
scanf("%s",buf1);
len = strlen (buf1);
ret = convert(buf1,len,&output);
if (ret! = 0)
{
printf("func convert() error!");
return ret;
}
printf("output:%d \n",output);
return 0;
}
2. Method 2 uses a secondary pointer
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int convert (char * myp, int mylen, int ** Poutput)
{
int i = 0;
char * pstart = myp + 1;
char * Pstop = myp + mylen - 1;
int ant = 0;
int hex = 1;
int *tmp = NULL;
tmp = (int *)malloc(10);
if(Pstop == NULL )
{
return -1;
}
if(myp == NULL)
{
return -1;
}
while(Pstop > pstart)
{
for(i = 0; i < mylen - 2; i++)
{
if(*Pstop >= 'A' && *Pstop <= 'F')
{
ant = ant + (*Pstop - 'A' + 10) * hex;
}
else
{
ant = ant + (*Pstop - '0') * hex;
}
Pstop -;
hex = hex * 16;
}
}
tmp = &ant;
*Poutput = tmp;
return 0;
}
intmain()
{
char buf1[10];
int *output = NULL;
int len = 0;
int ret = 0;
scanf("%s",buf1);
len = strlen (buf1);
ret = convert(buf1,len,&output);
if (ret! = 0)
{
printf("func convert() error!");
return ret;
}
printf("output:%d \n",*output);
return 0;
}