У меня есть программа для выполнения основных задач с двумя массивами символов.Все работает нормально, когда ограничение размера первого равно пределу размера второго, но когда размер первого массива char отличается от размера другого, программа начинает странным образом читать / записывать строки.
Например, если предел первого равен 31, а предел другого равен 5, если набранные символы в первом больше 8 или что-то в этом роде, программа не позволит пользователюнабрал что-нибудь во втором массиве, как будто он уже заполнен.
Я пытался исправить это, не используя функции string.h, но программы все равно делали то же самое, когда ограничение размера двух массивов символов былоразные.
#include <stdio.h>
#include <string.h>
#define LIMIT1 31
#define LIMIT2 5
/*Function: void copy_string(char *pointer_destination, char *pointer_source)
Precondition: it needs a pointer to the direction of memory of the first element of two char vectors and the size limit of the 'destination' vector
Postcondition: it puts all the elements of the 'source' vector into the other until the last element that */
void copy_string(char *pointer_destination, char *pointer_source, int LIMd){
//Variable declaration
int i = 0;
/*Cycle for replacing the element of the 'destination' vector by the element of the 'source' vector.
When the element of the 'destination' OR of the 'source' is the null character, this cycle ends*/
for(; i < LIMd && *(pointer_source + i) != '\0'; i++){
*(pointer_destination + i) = *(pointer_source + i);
}
*(pointer_destination + i) = '\0';
}
int main(){
//Variable declaration
int restart;
char username[LIMIT1], string2[LIMIT2];//Here we define the limit for obvious reasons
//Restart cycle starts here
do{
//Data input
printf("Type your username (maximum 30 characters)\n");
fgets(username, LIMIT1 - 1, stdin);
fflush(stdin);
printf("Type a string of maximum 30 characters\n");
fgets(string2, LIMIT2 - 1, stdin);
fflush(stdin);
printf("Your typed username and your typed second string are, respectively:\n");
fputs(username, stdout);
fputs(string2, stdout);
printf("Concatenating, the username is now\n");
strcat(username, string2);
fputs(username, stdout);
printf("Now I'll copy what is in your username and I'll put it in the second string,\n");
copy_string(string2, username, LIMIT2 - 1);
fputs(string2, stdout);
//Restart cycle switch
printf("Type '0' to close this program, otherwise it'll restart itself\n");
scanf("%d", &restart);
fflush(stdin);
//Restart cycle ends here
}while(restart);
return 0;
}
Я ожидал, что если бы размер двух массивов был разным, программа все равно считала бы и записала их правильно (если размер первого равен 3, читайте из пользователя только первыйтри символа и поставьте behing как \ 0, а если размер другого равен 25, сделайте то же самое, но с 25 как ограничение размера)