所以我正在嘗試學習如何在 C 中使用指標,并且我想創建一個結構來存盤亂數量的學生及其姓名和年齡。我正在盡力避免預先分配的靜態大小的陣列,因為我正在學習如何使用指標,這就是我被卡住的地方。
我基本上是在寫一個應用程式,要求輸入 n 個學生的姓名和年齡,直到給出的名字是stop并將資料存盤在結構中(使用 (ptr i)->studentName)等等(不是我已經還做了 for 回圈)。
這是我想出的:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
struct student_t{
char studentName[30];
int age;
}student_t;
int main() {
struct student_t *ptr;
ptr = (struct student_t*) malloc(10 * sizeof(struct student_t));
printf("Type student information: ");
scanf(" [^%s] %i", ptr->studentName, &ptr->age);
char a[10] = "stop";
if(ptr->studentName == a){
//exit when this is true
}
else
printf("%s %i", student_t.studentName, student_t.age);
printf("Type student information: ");
scanf("%s %i", (ptr 1)->studentName, &(ptr 1)->age);
//keep asking this until the if statement above is true and so on (maybe make a for loop?)
}
我知道我需要一個 for 回圈,int i但是,是的,我被卡住了。也不知道我應該在哪里使用 malloc() 和 realloc()...
有任何想法嗎?
uj5u.com熱心網友回復:
使用 讀取用戶輸入fgets()。
使用大容量的緩沖區。
用途sscanf()和各種說明符。例如"%n",記錄掃描的偏移量。%*s掃描一個詞,但不保存。
測驗輸入的完整性。
#define AGE_MIN 0
#define AGE_MAX 120
#define FNAME_SIZE 100
#define LNAME_SIZE 200
#define INT_SIZE 12
// first space last space number \n \0
char buffer[FNAME_SIZE 1 LNAME_SIZE 1 INT_SIZE 1 1];
printf("Type student information: ");
if (fgets(buffer, sizeof buffer, stdin)) {
int name1;
int name2;
// skip leading space
// Record offset
// scan a name
// scan a single space
// scan a name
// Record offset
// scan a int
if (sscanf(buffer, " %n%*s%*1[ ]%*s%n %d",
&name1, &name2, &ptr->age) == 1) {
if (ptr->age < AGE_MIN || ptr->age > AGE_MAX) {
// age issue
TBD_error_code();
}
// Test full name size
unsigned len = name2 - name1;
if (len >= sizeof ptr[j].studentName) {
// name too big
TBD_error_code();
}
memcpy(ptr[j].studentName, buffer name1, len);
ptr[j].studentName[len] = '\0';
printf("%s %i", student_t.studentName, student_t.age);
}
uj5u.com熱心網友回復:
所以,我試圖找到一種方法來幫助你,并得到了它。您可以使用 while 回圈,使用函式strcmp(str1, str2)作為退出條件,并使用索引 i 在 ptr 中導航。在回圈內部,你可以直接重新分配ptr。
int main()
{
struct student_t *ptr = malloc (sizeof(struct student_t));
char a[10] = "stop";
int i = 0;
// you can use a while loop with that condition.
while (strcmp(ptr[i - 1].studentName, a) != 0)
{
// condition that check if we can realloc or not.
ptr = (i != 0) ? (struct student_t*) realloc (ptr, sizeof(struct student_t) * (i 1)) : ptr;
printf ("Type student information: ");
scanf ("%s %i", ptr[i].studentName, &ptr[i].age);
i ;
// for loop to display ptr's information.
for (int j = 0; j < i; j )
{
printf ("%s %i \n", ptr[j].studentName, ptr[j].age);
}
}
free (ptr) ;
return 0;
}
(ptr i) 等價于 ptr[i]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/352384.html
