Hi, everyone.
I tried to handle my character pointer in the function but it's not easy..
At first, I allocate 3 lenths of character string and set as "EOF" out of function "strToHexa".
And then tried to make expand space to put 6 lengths of other strings with same character pointer by freeing and allocating memory again in the function. So I used double pointer as a parameter of function.
Code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <mem.h>
void strToHexa(char **string)
//convert characters to hexadecimal
{
char toHexa[3];
int i;
int sLen=strlen(*string);//set the length of the original string into "sLen"
printf("in strToHexa[before] : %p\n", *string);//result: "0090B928"
if(sLen<=3){//if the length of original string is less than 3 (3 lengths is my limitation.
strcpy(toHexa, *string);//copy original strings to arrays
free(*string);//free original
*string=(char *)malloc(sizeof(char)*sLen*2);//allocate memory with 2 times of the original string because one character needs two characters to express hexadecimal
for(i=0;i<sLen;i++){
sprintf((*string)+(i*2), "%X", toHexa[i]);
}
}
printf("in strToHexa[after] : %p\n", *string); //result: "0090B928"
}
int main(void)
{
char *test=(char *)malloc(sizeof(char)*3);
strcpy(test, "EOF");
printf("[before] %p\n", test); //result: "0090B928"
printf("test: %s\n", test); // result: "EOF"
strToHexa(&test);
printf("[after] %p\n", test); //result: "FFFFFFFF"
printf("test: %s\n", test); // segmatation fault! I wanned to see "454F46" which is hexadecimal form of "EOF"
return 0;
}
Here is my another trying. It's simple and goes in right way.
Code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <mem.h>
void setStr(char **string)
{
printf("in[before] %p\n", *string);
free(*string);
*string=(char*)malloc(sizeof(char)*4);
strcpy(*string, "ABCD");
printf("in[after] %p\n", *string);
}
int main(void)
{
char *test=(char *)malloc(sizeof(char)*2);
strcpy(test, "EO");
printf("[before] %p\n", test);
printf("test: %s\n", test);
setStr(&test);
printf("[after] %p\n", test);
printf("test: %s\n", test);
return 0;
}
The result is as follow.
[before] 009029B8
test: EO
in[before] 009029B8
in[after] 009029B8
[after] 009029B8
test: ABCD