maheshptl
asked on
pass pointer to char and should return pointer char of corresponding ASCII values
Hi all,
Its my first quesion, which was asked for me in interview.
write function which talks pointer to char and returns pointer to char of ASCII values of corresponding char. For example, if i pass string "abcde" to function , it should return pointer to string "6162636465", (that is a=65,b=62,.....). Plz help me,
Its my first quesion, which was asked for me in interview.
write function which talks pointer to char and returns pointer to char of ASCII values of corresponding char. For example, if i pass string "abcde" to function , it should return pointer to string "6162636465", (that is a=65,b=62,.....). Plz help me,
Do u actually want code for this,or u just looking for an explanation to the answer.
This is quite simple and i am actually surprised that this could be asked at an interview,
May i dare ask,which company??
This is quite simple and i am actually surprised that this could be asked at an interview,
May i dare ask,which company??
BTW,
"ABCDE" should return "6566676869"
"abcde" would return "979899100101"
"ABCDE" should return "6566676869"
"abcde" would return "979899100101"
Here is the code:
#include<string.h>
char * func(char*);
int main()
{
char *ptr="ABCDE";
char *p;
p=func(ptr);
printf("%s",p);
}
char * func(char *s)
{
char str[100];//declare to any large size
char temp[5];//enough for string version for ASCII of 1 character
int i;
strcpy(str,"");
while(*s!='\0')
{
i=*s;
itoa(i,temp,10);
strcat(str,temp);
s++;
}
return str;
}
#include<string.h>
char * func(char*);
int main()
{
char *ptr="ABCDE";
char *p;
p=func(ptr);
printf("%s",p);
}
char * func(char *s)
{
char str[100];//declare to any large size
char temp[5];//enough for string version for ASCII of 1 character
int i;
strcpy(str,"");
while(*s!='\0')
{
i=*s;
itoa(i,temp,10);
strcat(str,temp);
s++;
}
return str;
}
char * func(char *s){
char *str=malloc(2*strlen(s)+1) ;
int i;
for( i=0;s[i]; i+=1 ){
sprintf(&str[2*i],"%02x",s [i]);
}
return str;
}
char *str=malloc(2*strlen(s)+1)
int i;
for( i=0;s[i]; i+=1 ){
sprintf(&str[2*i],"%02x",s
}
return str;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
These "interview questions" always leave me scratching my head.... They don't provide a operational purpose and I'm not convinced of their "evalutation" value.
Taking the above mentioned examples another step:
char * func(char *s)
{
char *ptr;
char *str=malloc(3*strlen(s)+1)
ptr = str;
while (*s)
{
sprintf (ptr, %d,*(s++));
ptr+=2;
}
*ptr = 0;
return str;
}
for "abcde",O/P should be "6566676869"
That's pretty simple.
cast each character into an integer,use itoa() to make it into a string and use strcat() to append it to ur final string.
Then return the address of this char array(string).