這個問題在這里已經有了答案: 字符陣列應該如何用作字串? (4 個回答) 從 fgets() 輸入中洗掉尾隨換行符 14 個答案 8 小時前關閉。
為什么當我嘗試在變數中獲取文本時不會存盤在完整的句子中。malloc似乎沒有為字串分配足夠的記憶體,為什么?
所以對于“第二”變數,當我輸入“不高興為什么”但“第二”只存盤“不”時,應該有足夠的空間用于字串,為什么?
當我嘗試下面的代碼時:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Function Declerations */
char *str;
char *second;
/* Global Variables */
int main(){
/* Initializing Global Variables */
/* EXPERIMENTING WITH FGETS */
/* Initial memory allocation */
str = malloc(5 * sizeof(char));
second = malloc(200 * sizeof(char));
/* Get user input and print results */
printf("Enter a string: "); // ask user to put in a string
fgets(str, sizeof(str), stdin);
str[strlen(str) - 1] = '\0'; // Removes new line character of fgets
printf("Enter a another string: "); // ask ujason is a godser to put in a string
fgets(second, sizeof(second), stdin);
second[strlen(second) - 1] = '\0'; // Removes new line character of fgets
printf("String = %s, Address of String is = %p\n", str, str);
printf("String = %s, Address of String is = %p\n\n\n", second, second);
/* Reallocating memory */
str = (char *)realloc(str, (100 * sizeof(char)));
printf("Combine text\n");
strcat(str, second);
printf("String = %s, Address of String is = %p\n", str, str);
printf("String = %s, Address of String is = %p\n\n\n", second, second);
free(str);
free(second);
return 0;
}
/* Function Details */
輸出是:
Enter a string: jason
Enter a another string: is not happy why
String = jason, Address of String is = 00000000001C2460
String = is no, Address of String is = 00000000001C5FD0
Combine text
String = jason is no, Address of String is = 00000000001C70B0
String = is no, Address of String is = 00000000001C5FD0
uj5u.com熱心網友回復:
好的,所以當您呼叫 fgets 時,您傳遞了指標的大小。不是它所指向的大小。
因此,例如,現在它正在作業:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Function Declerations */
char *str;
char *second;
/* Global Variables */
int main(){
/* Initializing Global Variables */
/* EXPERIMENTING WITH FGETS */
/* Initial memory allocation */
str = (char*) malloc(7 * sizeof(char));
second = (char*) malloc(200 * sizeof(char));
/* Get user input and print results */
printf("Enter a string: "); // ask user to put in a string
fgets(str, 7, stdin);
str[strlen(str)] = '\0'; // Removes new line character of fgets
printf("Enter a another string: "); // ask ujason is a godser to put in a string
fgets(second, 200, stdin);
second[strlen(second)] = '\0'; // Removes new line character of fgets
printf("\nString = %s, Address of String is = %p\n", str, str);
printf("String = %s, Address of String is = %p\n\n\n", second, second);
/* Reallocating memory */
str = (char *)realloc(str, (100 * sizeof(char)));
printf("Combine text\n");
strcat(str, second);
printf("String = %s, Address of String is = %p\n", str, str);
printf("String = %s, Address of String is = %p\n\n\n", second, second);
free(str);
free(second);
return 0;
}
您需要將實際大小而不是指標的大小傳遞給 fgets :)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/473139.html
上一篇:有沒有辦法動態使用fgets大小
