【问题标题】:How to iterate over a char** in C?如何在C中迭代一个char**?
【发布时间】:2020-11-01 16:46:30
【问题描述】:

如何遍历 char ** 数组?以及如何获取每个位置的值(获取key1、key2、key3)? 我有这个:

// Online C compiler to run C program online
#include <stdio.h>
#include <string.h>

int main() {
    
    char **tree_keys = {"key1","key2","key3"};
    printf("Key = %s\n", tree_keys);
    int size = 0;
     int i =0;
   while(tree_keys[i] != '\0'){
       size++;
       i++;
   }
     printf("%s", size);
   

    return 0;
}```

it returns segmentation fault

【问题讨论】:

  • 这能回答你的问题吗? What does int argc, char *argv[] mean?
  • 问题三:首先初始化无效;那么tree_keys 不是字符串,不能这样使用(就像你对printf 所做的那样);而且它不会自动终止。不要在这里使用指向指针的指针,而是使用 array 指针:char const *tree_keys[] = { "key1", "key2", "key3", NULL };

标签: arrays c


【解决方案1】:

首先,您不能以这种方式初始化字符串数组。这里有两种方法:

int string_count = 3;
char **tree_keys = malloc(string_count * sizeof(char *));
if (tree_keys == NULL) exit(1);
tree_keys[0] = "key1";
tree_keys[1] = "key2";
tree_keys[2] = "key3";
char *tree_keys[] = { "key1", "key2", "key3" };

当然,第二种方式比第一种方式更可取,因为您不需要使用malloc

在你有一个初始化的数组之后,你可以像这样迭代:

int size = 0, string_count = 3;
for (int i = 0; i < string_count; i++) {
    char *ptr = tree_keys[i];
    while (*ptr != '\0') {
        size++;
        ptr++;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2012-11-19
    • 2023-03-13
    • 1970-01-01
    • 2015-08-14
    相关资源
    最近更新 更多