I am trying to write a program that will conjugate a verb in multiple forms.
So I write a function that will allow me to get the part that is kepted and conjugate it. Fixed rule : whole word except last 2 chars.
I am used to OO, and I can't seem to make it work, while it seems a basic program.
I obtain something with weird : here is a screen at the end of the execution, that will be more explicit
I think I missed a little something in my course (probably in the char[] part...), that has a huge impact, but I can't seem to find it. I am opened to all observations on my code, since I am beginning, and I prefer going on a solid basis right now, better that later.
Here is the code
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void RacineVerbe(char verbeEntier[], char dest[]);
int myStrLen(char *s);
int main()
{
char *string;
char *racine;
string = (char*)malloc(200*sizeof(char));
racine = (char*)malloc(200*sizeof(char));
printf("Quel verbe?\n");
scanf("%s", string);
RacineVerbe(string, racine);
printf("%s", racine);
printf("%sASSE\n", racine);
printf("%sASSES\n", racine);
printf("%sAT\n", racine);
printf("%sASSIONS\n", racine);
printf("%sASSIEZ\n", racine);
printf("%sASSENT\n", racine);
return 0;
}
void RacineVerbe(char verbeEntier[], char dest[]){
int i;
int l = myStrLen(verbeEntier);
for( i = 0; i < l -2 ; i++){
dest[i] = verbeEntier[i];
}
dest[i+1] = "\0";
}
int myStrLen(char *s){
int i = 0;
while(*s++)i++;
return i;
}
You invoked UB when you wrote dest[i+1] = "\\0";
since dest[i+1]
expects a char
and you assigned "\\0"
into it, which is a string literal. Replace it with '\\0'
Note that string = (char*)malloc(200*sizeof(char));
---> string = malloc(200);
since casting is not needed in malloc
in C, and considered bad ( as you can see here ) and also sizeof(char)
is, by definition, 1
The problem is in you RacineVerbe
because you assigned string literal to single character (not a poitner to characters).
In that situation, string literal returns you the address where it is in memory and you assigned to dest[i+i]
LSB byte of that address and it may be or may not be visible character. I can assure, your compiler gave you at least warning for that.
Second problem is where you did assignment. You should do it to dest[i]
as i
was last time incremented in for
loop before check failed and therefore i
already points to place where 0
should be written.
void RacineVerbe(char verbeEntier[], char dest[]){
int i;
int l = myStrLen(verbeEntier);
for( i = 0; i < l -2 ; i++){
dest[i] = verbeEntier[i];
}
dest[i] = 0; //This line was rewritten.
}
And as already mentioned, try to NOT cast return result of malloc
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.