【问题标题】:Python-like array filling - C equivalent类似 Python 的数组填充 - C 等效
【发布时间】:2025-12-17 19:20:03
【问题描述】:

我想知道在 Python 中填充数组的等效方法,但在 C 中。

Python 示例代码:

arrayname=[0]*10
randomtextvar="test_text"
for i in range(10):
    arrayname[i]=randomtextvar
for k in range(10):
    print(arrayname[k]+" "+str(k)+ " position")

我还没有找到解决方案,我真的不明白如何将值设置为字符串 (char) 数组位置(在 C 中)

编辑:

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

int main() {
    int c = 0;
    char arr[256];
    fgets(arr, 256, stdin);
    char spl[] = " ";
    char *ptr = strtok(arr, spl);
    while (ptr != NULL) {
        ptr = strtok(NULL, spl);
        // HERE I WANT TO ADD THE ptr value to a new array of strings
        c++;
    }
    return 0;
}

【问题讨论】:

  • 'valorize' 是什么意思?
  • 我的意思是设置值,翻译错误,已经编辑,抱歉。
  • 请尽可能多地显示您已经知道如何操作的代码。不清楚你到底不明白什么。您要复制字符串还是引用相同的字符串?你知道如何声明一个数组吗?你知道指针吗?你知道如何复制字符串吗?
  • 搜索“C 字符串数组”没有找到任何有用的信息?如thisthisthis等。
  • 你可以这样做:char *string_array[10]; int i = 0; ... string_array[i++] = strdup(ptr);。请注意,strdup 分配动态内存,因此您在不再需要时需要free。另外,需要确保数组没有溢出。

标签: arrays c


【解决方案1】:

您在while 循环之前执行strtok,并在开始时立即。因此,您正在丢弃行中的第一个标记。

kaylum 指出了一种使用strdup 将字符串保存到固定 数组的简单方法。

但是,我怀疑您想要像 python 所做的那样灵活的东西。因此,当您使用 realloc 处理 许多 输入行时,字符串数组可以动态增长。

此外,有时最好让最后一个数组元素为NULL [就像argv]。

这是一些重构的代码。我已经对其进行了注释以解释发生了什么:

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

int
main(void)
{
    char *ptr;
    char *bp;
    const char *spl = " \n";
    char buf[256];
    char **arr = NULL;
    size_t arrcnt = 0;
    size_t arrmax = 0;

    // read in all input lines
    while (1) {
        // get next input line -- stop on EOF
        ptr = fgets(buf,sizeof(buf),stdin);
        if (ptr == NULL)
            break;

        // parse the current line
        bp = buf;
        while (1) {
            // get next token on the current line
            ptr = strtok(bp,spl);
            bp = NULL;

            // stop current line if no more tokens on the line
            if (ptr == NULL)
                break;

            // grow the string array [periodically]
            // NOTE: using arrmax cuts down on the number of realloc calls
            if (arrcnt >= arrmax) {
                arrmax += 100;
                arr = realloc(arr,sizeof(*arr) * (arrmax + 1));
                if (arr == NULL) {
                    perror("realloc/grow");
                    exit(1);
                }
            }

            // add current string token to array
            // we _must_ use strdup because when the next line is read any
            // token data we had previously would get overwritten
            arr[arrcnt++] = strdup(ptr);

            // add null terminator just like argv -- optional
            arr[arrcnt] = NULL;
        }
    }

    // trim the array to the exact number of elements used
    arr = realloc(arr,sizeof(*arr) * (arrcnt + 1));
    if (arr == NULL) {
        perror("realloc/trim");
        exit(1);
    }

    // print the array
    for (char **av = arr;  *av != NULL;  ++av)
        printf("%s\n",*av);

    // free the array elements
    for (char **av = arr;  *av != NULL;  ++av)
        free(*av);

    // free the array
    free(arr);

    // reset counts and pointer
    arrmax = 0;
    arrcnt = 0;
    arr = NULL;

    return 0;
}

【讨论】: