[英]How to store a string in a multidimensional array in C
我是 C 的新手,我正在嘗試做一個要求插入一些字符串然后存儲它們的練習。 首先,它請求一個多維數組,其中數組的每一行都有一個字符串,然后是一個指針數組。 這是第一部分的代碼。 我不知道如何將一些尚未寫入的字符串存儲到數組中。
對於第二個我不知道,因為我以前從未用指針做過練習。
#include <stdio.h>
int main(){
int n; //number of strings
int x; //number of characters per string
printf("How many strings do you want to insert?");
scanf("%d", &n);
if ((n >= 1) && (n <= 20)){
printf("How many characters per string?");
scanf("%d", &x);
char str[x];
if (x <= 10){
for(int i = 0; i < n; i++){
printf("Insert a string:");
scanf("%s", str);
for(int j = 0; j < x; j++){
char arr[j];
arr[j] = str[x];
printf("%s", arr);
}
}
}
else {
printf("Error:the number of characters must be < 10");
}
}
else {
printf("Error: the number must be < 20");
}
return 0;
}
...請求一個多維數組,其中數組的每一行都有一個字符串,然后是一個指針數組。
在獲得合格的字符串數量后,分配一個指向char
的指針數組。
if ((n >= 1) && (n <= 20)){
char **string_list = calloc(n, sizeof *string_list);
assert(string_list); // or other error checking
(注意沒有 type in = calloc(n, sizeof *string_list);
。更容易正確編碼、查看和維護。)
讀取工作臨時緩沖區中的字符串。 作為“每個字符串有多少個字符?” 可能意味着不包括null 字符的字符數,我們的str[]
需要 +1 大小。
// char str[x]; // too small
char str[x+1];
然而我們知道x <= 10
並且可以使用固定的緩沖區大小並限制輸入長度
for(int i = 0; i < n; i++){
char str[10+1];
printf("Insert a string:");
scanf("%10s", str); // Notice the 10 - a width limit
// TBD check if scanf() returned 1 and if str is longer than x
現在分配str
的副本
string_list[j] = strdup(str);
assert(string_list[j]); // or other error checking
}
稍后,當使用string_list[]
完成時,清理和釋放分配。
for (int i=0; i<n; i++) {
free(string_list[i]);
}
free(string_list);
這有什么弱點:
它使用scanf()
而不是fgets()
然后解析,具有最少的錯誤檢查,不接受帶空格的字符串,不處理過長的輸入, strdup()
還不是標准的,等等。
所以上面是一個嬰兒步驟。 更好的代碼將處理薄弱的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.