简体   繁体   English

将元素动态添加到数组 C

[英]Dynamically adding elements to array C

I am trying to build a function that takes a string of chars and provides a list of those chars separated by a token.我正在尝试构建一个函数,该函数接受一串字符并提供由标记分隔的这些字符的列表。

This is what I have so far:这是我到目前为止:

char * decode_args(char arguments[]){
  char* token = strtok(arguments, "00");
  while (token != NULL){
    printf("%s\n", token);
    token = strtok(NULL, "00");
  }
  return 0;
}

This function prints the desired values that I am looking for.此函数打印我正在寻找的所需值。 For example:例如:

>decode_args("77900289008764")
779
289
8764

The next step is to build an array that can be used in the execv command.下一步是构建一个可以在execv命令中使用的数组。 The arguments need to be an array.参数必须是一个数组。 An example here . 这里有一个例子 I am a beginner so I don't even know if "array" is the right word.我是初学者,所以我什至不知道“数组”是否正确。 What data type should be built and how can I do that so I can call execv with the arguments that are currently being printed in a list?应该构建什么数据类型,我该怎么做才能使用当前打印在列表中的参数调用execv

For starters let me explain some stuff about storage and strings.首先,让我解释一些有关存储和字符串的内容。

There are 3 basic storage types.有 3 种基本存储类型。 Automatic, dynamic, static.自动、动态、静态。 And static one usually split into two: read-only and read-write.而静态的通常分为两种:只读和读写。 Dynamic and static ones will be useful for you soon.动态和静态的很快就会对你有用。

Automatic variables are function parameters and local variables.自动变量是函数参数和局部变量。 When you call a function they pushed into stack and when function returns they got unwind.当你调用一个函数时,它们会被压入堆栈,当函数返回时,它们会放松。

Dynamic one is the one you allocate in runtime with malloc family.动态一个是您在运行时使用malloc系列分配的一个。 This is how we create a dynamic array.这就是我们创建动态数组的方式。 And you need to return this source when you are done with free .完成free ,您需要返回此源。 If you don't, it is called memory leak and you can check for memory leaks with the tool valgrind beside other memory errors.如果不这样做,则称为内存泄漏,除了其他内存错误之外,您还可以使用valgrind工具检查内存泄漏。 It is quite useful for systems programming class.它对于系统编程类非常有用。

And static ones are the ones stay there for lifetime of the program.静态的是在程序的整个生命周期中都留在那里的。 If you define a global variable or static int i = 42 it will create static read-write variable so you can change it.如果您定义一个全局变量或static int i = 42 ,它将创建静态读写变量,以便您可以更改它。 Now here is the trick.现在这是诀窍。

void foo() {
   char *string1 = "hello, world" //static read-only
   char string2[] = "hello, world" //automatic
}

So if you try to change string1 you will get a segmentation fault but it is OK to change string2 .因此,如果您尝试更改string1 ,则会出现分段错误,但可以更改string2 I don't know why you don't get segmentation fault by doing decode_args("77900289008764") but I get on my machine.我不知道为什么你没有通过decode_args("77900289008764")得到分段错误,但我进入了我的机器。 :D :D

Now C-strings.现在是 C 弦。 They are null terminated which means there is a (char) 0 character end of each string that says it is end of the string.它们以空字符结尾,这意味着每个字符串都有一个(char) 0字符结尾,表示它是字符串的结尾。 strtok basically replace the pattern with NULL character so you have multiple substrings instead of one. strtok基本上用NULL字符替换模式,因此您有多个子字符串而不是一个。 So from your example it converts "77900289008764 NULL" to "779 NULL 289 NULL 8764 NULL"因此,从您的示例中,它将"77900289008764 NULL"转换为"779 NULL 289 NULL 8764 NULL"

So if I were you I would count encounters of "00" in the string and allocate that much character pointer.因此,如果我是你,我会计算字符串中遇到“00”的次数并分配那么多的字符指针。 Which is something like:这类似于:

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

char ** decode_args(char *arguments, char *delim) {
    int num_substrings = 1; // Note that C don't initialize with 0 like java etc.
    int len_delim = strlen(delim);

    for (int i = 0;
            arguments[i] != '\0' && arguments[i + 1] != '\0'; // Any of last 2 chars are terminator?
            ++i)
        if (strncmp(arguments + i /* same as &arguments[i] */, delim, len_delim) == 0)
            ++num_substrings;

    char **result = (char **) malloc(sizeof(char *) * (num_substrings + 1));
    int i = 0;
    char* token = strtok(arguments, delim);

    while (token != NULL){
        result[i] = token;
        ++i;
        token = strtok(NULL, delim);
    }

    result[i] = NULL; //End of results. execv wants this as I remember

    return result;
}
int main(int argc, char *argv[])
{
    char str[] = "foo00bar00baz";
    char **results = decode_args(str, "00");

    for (int i = 0; results[i] != NULL; ++i) {
        char *result = results[i];
        puts(result);
    }

    free(results);

    return 0;
}

Try something like this:尝试这样的事情:

#define MAX_ARGUMENTS 10

int decode_args(char arguments[], char ** pcListeArgs)
{
    int iNumElet = 0;
    char* token = strtok(arguments, "00");

    while ((token != NULL) && (iNumElet < MAX_ARGUMENTS -1)) 
    {
        size_t len = strlen(token);

        pcListeArgs [iNumElet] = (char*) calloc (len+1, sizeof (char));
        memset(pcListeArgs [iNumElet], 0, len+1); // reset content
        memcpy(pcListeArgs [iNumElet], token, len); // copy data

        token = strtok(NULL, "00");
        iNumElet++;
    }

    if ( iNumElet >= MAX_ARGUMENTS)
        return -1;

    return iNumElet;
}

And int the main :和 int 主要:

int main() {

    char *pListArgs[MAX_ARGUMENTS];

    char args[] = "77900289008764";

    int iNbArgs = decode_args (args, pListArgs);

    if ( iNbArgs > 0)
    {
        for ( int i=0; i<iNbArgs; i++)
            printf ("Argument number %d = %s\n", i, pListArgs[i]);

        for ( int i=0; i<iNbArgs; i++)
            free (pListArgs[i]);
    }

    return 0;
}

output:输出:

在此处输入图片说明

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

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