I'm using the gcc compiler I installed which I run from my cmd (write in the editor visual code) & for debugging I also installed visual studio.
It's my second semester and I just learned about malloc
/calloc
etc.
so the line:
ch_pointer = (char *)malloc(length * sizeof(char));
in my gcc compiler gives in return when I use strlen(ch_pointer)
, 2
or 4
as an answer.
If I use a number too big (example 100) for length it also just says strlen(ch_pointer) == 0
.
It works perfectly fine if I write it in visual studio as:
ch_pointer = (char *)malloc(((length + 1) * sizeof(char)) / 2 - 1);
and that's the only case it worked perfectly.
get_number()
function is fine it's just making sure you will type an int type.
void main() {
char *ch_pointer = '\0';
int length = 0;
printf("Please write down your sentence length in characters (including spaces): ");
length = get_number();
ch_pointer = (char *)malloc(((length + 1) * sizeof(char)) / 2 - 1);
ch_pointer[strlen(ch_pointer) - 1] = '\0';
printf("Please write down your sentence: ");
for (int filling = 0; filling < strlen(ch_pointer); filling++)
scanf(" %c", &ch_pointer[filling]);
for (int printing = 0; printing < strlen(ch_pointer); printing++)
printf("%c", ch_pointer[printing]);
free(ch_pointer);
}
For both compilers to work the same if I write down 4
or even 100
to get an array length 5
or 101
that ends in '\0'
& let me type and print perfectly:
length = 4
strlen(ch_pointer) == 4
or
length = 100
strlen(ch_pointer) == 100