简体   繁体   English

如何将字符串存储在C中的多维数组中

[英]How to store a string in a multidimensional array in C

I'm new at C and I'm trying to do an exercise which asks to insert some strings and then store them.我是 C 的新手,我正在尝试做一个要求插入一些字符串然后存储它们的练习。 First it requests a multidimensional array where we have for every row of the array a string, and then as an array of pointers.首先,它请求一个多维数组,其中数组的每一行都有一个字符串,然后是一个指针数组。 Here's the code for the first part.这是第一部分的代码。 I don't know how to store into an array some strings that are not already written.我不知道如何将一些尚未写入的字符串存储到数组中。

For the second one I have no idea since I've never done exercises with pointers before.对于第二个我不知道,因为我以前从未用指针做过练习。

#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;
}


... requests a multidimensional array where we have for every row of the array a string, and then as an array of pointers. ...请求一个多维数组,其中数组的每一行都有一个字符串,然后是一个指针数组。

After getting the qualified number of strings, allocate an array of pointers to char .在获得合格的字符串数量后,分配一个指向char的指针数组。

if ((n >= 1) && (n <= 20)){
  char **string_list = calloc(n, sizeof *string_list);
  assert(string_list);  // or other error checking

(Notice no type in = calloc(n, sizeof *string_list); . Easier to code right, review and maintain.) (注意没有 type in = calloc(n, sizeof *string_list); 。更容易正确编码、查看和维护。)

Read the strings in a working temp buffer.读取工作临时缓冲区中的字符串。 As "How many characters per string?"作为“每个字符串有多少个字符?” likely means the number of characters not including the null character , our str[] needs a +1 in size.可能意味着包括null 字符的字符数,我们的str[]需要 +1 大小。

        // char str[x]; // too small
        char str[x+1];

Yet we know x <= 10 and can use a fixed buffer size and limit input length然而我们知道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

Now allocate a copy of the str现在分配str的副本

        string_list[j] = strdup(str);
        assert(string_list[j]);  // or other error checking
      }

Later, when done with string_list[] , clean-up and free allocations.稍后,当使用string_list[]完成时,清理和释放分配。

for (int i=0; i<n; i++) {
  free(string_list[i]);
}
free(string_list);

What is weak about this:这有什么弱点:

It uses scanf() rather than fgets() and then parses, has minimal error checking, does not take in strings with spaces, does not handle over-long input, strdup() is not standard -yet , etc.它使用scanf()而不是fgets()然后解析,具有最少的错误检查,不接受带空格的字符串,不处理过长的输入, strdup()还不是标准的,等等。

So the above is a baby step.所以上面是一个婴儿步骤。 Better code would handle the weak issues.更好的代码将处理薄弱的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM