簡體   English   中英

將字符串復制到char數組中

[英]Copy a string into a char array

您好,我想將用戶的輸入復制到結構體中定義的char數組中。 真誠的我不知道該怎么做。

#include <stdio.h>
#include <stdlib.h>


int main ()

{
    struct employee
    {
        char firstname[11];
        char lastname[11];
        char number[11];
        int salary;
    }

    int i;
    int nemps;
    const int maxemps = 5;
    struct employee* emps[maxemps];

    printf("How many employees do you want to store?(max:5): ");
    scanf("%d", nemps);

    for (i = 0; i < nemps; i++)
    {
        printf("Employee 1./nLast name:");
        scanf("....")// Read the string and copy it into char lastname[]
    }

}

首先是struct employee* emps[maxemps]; 創建一個指針數組來構造數組大小為maxemps的 雇員 您實際上並未在內存中為實際結構留出任何空間,只是會指向它們的指針。 為了為結構動態分配堆上的空間,以便可以有意義的方式使用它們,您需要像下面這樣循環調用malloc()

for (i = 0; i < maxemps; i++) {
   emps[i] = malloc(sizeof(struct employee));
}

您還需要在程序末尾進行類似的循環,該循環將free()每個指針。

接下來,當您從用戶那里獲取輸入時,您確實希望在scanf()上使用fgets() ,因為fgets()允許您指定要讀取的字符數,從而可以防止目標緩沖區溢出。

更新

如果要使用單個struct employee而不使用指針,可以通過在堆棧上聲明一個或多個struct employee ,然后使用來實現. 成員訪問運算符如下:

struct employee emp;
fgets(emp.lastname, sizeof(emp.lastname), stdin);

UPDATE2

我在您的代碼中發現了許多錯誤。 請查看此鏈接以獲取帶有注釋的工作示例。

您只需要:

scanf("%10s", (emps[i])->last_name);

此處的"%10s"表示最大長度為10的字符串,它將字符串加載到last_name。

在C中,字符串表示為char數組,結尾為'\\0'

如果用戶輸入的長度超過10,則在此處使用scanf容易受到緩沖區攻擊: http : //en.wikipedia.org/wiki/Scanf#Security ,因此您需要為該格式分配最大長度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM