Python-like array filling - C equivalent

别来无恙 提交于 2021-02-16 21:08:45

问题


I would like to know what would be the equivalent for filling an array like we do in Python, but in C.

Python example code:

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")

I haven't find an solution for this, I don't really understand how to set value to a string (char) array position (in C).

EDIT:

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

回答1:


You are doing strtok before the while loop and immediately at the start. So, you are trashing the first token on the line.

kaylum pointed out a simple way to save the strings into a fixed array using strdup.

But, I suspect you'd like something as flexible as what python is doing. So, the array of strings can be dynamically grown as you process many input lines using realloc.

Also, in addition, it's sometimes nice to have the last array element be NULL [just like argv].

Here's some refactored code. I've annotated it to explain what is going on:

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


来源:https://stackoverflow.com/questions/65605903/python-like-array-filling-c-equivalent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!