如何存储字符串数组以便以后可以引用?

时间:2019-09-29 01:42:40

标签: c

   int counter = 0; 
   while(1) {
      char *arr[9];
      // performing string parsing, results will be put into arr
      counter++;
    }

假设在循环中我声明了一个字符串数组,程序将执行一些解析,并将结果存储到该数组中。下次,该过程再次发生,因此将清除数组中的内容。

如何存储数组的内容,以便以后可以在程序中引用该数组:history[counter] // the content should be arr at that point of execution

1 个答案:

答案 0 :(得分:0)

如果您的字符串解析产生了一些动态分配的字符串,那么您可以将其复制到循环末尾的历史记录数组中。

在下一个循环遍历中,您可以访问arr中的新值和历史记录中的先前值。第一次循环传递很特别,您必须小心,因为在这种情况下,您没有任何历史值。

为了拥有一个自包含的示例,而不是真正地解析代码,而是动态地创建一些字符串。

在代码中,它可能看起来像这样:

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


char *some_str(int counter, int index) {
    char *result = malloc(32);
    sprintf(result, "arbitrary %d_%d", counter, index);
    return result;
}

#define NUM 2

int main() {
    char *history[NUM];
    memset(history, '\0', sizeof history);

    int counter = 0;
    while(1) {
        char *arr[NUM];

        //fill arr with some dynamically allocated strings
        for(int i = 0; i < NUM; i++) {
            arr[i] = some_str(counter, i);
        }

        //here you can access both, new arr and history values at the same tme
        for(int i = 0; i < NUM; i++) {
            char *hist =  history[i];
            if(hist == NULL) {
                hist = "none";
            }
            printf("history[%d]='%s' and arr[%d]='%s'\n", i, hist, i, arr[i]);
        }
        printf("\n");

        //free current history if available and copy arr
        for(int i = 0; i < NUM; i++) {
            if(history[i]) {
                free(history[i]);
            }
            history[i] = arr[i];
        }
        if(counter == 3)
            break;
        counter++;
    }

    //finally free remaining dynamically allocated strings
    for(int i = 0; i < NUM; i++) {
        if (history[i]) {
            free(history[i]);
        }
    }
    return 0;
}

控制台输出为:

history[0]='none' and arr[0]='arbitrary 0_0'
history[1]='none' and arr[1]='arbitrary 0_1'

history[0]='arbitrary 0_0' and arr[0]='arbitrary 1_0'
history[1]='arbitrary 0_1' and arr[1]='arbitrary 1_1'

history[0]='arbitrary 1_0' and arr[0]='arbitrary 2_0'
history[1]='arbitrary 1_1' and arr[1]='arbitrary 2_1'

history[0]='arbitrary 2_0' and arr[0]='arbitrary 3_0'
history[1]='arbitrary 2_1' and arr[1]='arbitrary 3_1'

如果没有动态分配的字符串,则可以使用strdup