I want to create a function that takes a char or a string in C, so i the argument of the function is a char pointer.
int code(char* mot){
char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
if (strlen(mot) > 1){
// If we give a word
int longueur = strlen(mot);
int resultat = 0;
for (int i=1; i<longueur+1; i++){
char l = mot[i-1];
printf("%c\n", l);
resultat += pow(26, (i-1))*code(&l);
}
return resultat;
} else if (strlen(mot) == 1){
// If we give a char
char letter = *mot;
char* pPosition = strchr(alphabet, letter);
int index;
if (pPosition != NULL){
index = pPosition - alphabet + 1;
}
return index;
} else {
printf("ERROR: length of word not valid");
return -1;
}
}
My function works if I replace resultat += pow(26, (i-1))*code(&l);
with that resultat += pow(26, (i-1))*code("a");
. I don't understand why when I use the pointer it don't take the char associated with the pointer. Altough, it displays me a segmentation fault error.
@Barmar answered my question in comment.
it was the strlen
function that cannot be used for char
type.
I will create two different functions to resolve the problem.
Thank you @Barmar , @001 and @Ian Abott for your time.