1

我正在尝试解析 envp 数组以获取程序的变量名称和值(稍后将使用),但我想我在 realloc 方面还不够好,有人可以帮我吗?

void envset(char *envp[]) {
   char *name = NULL;
   char *value = NULL;
   char *temp = NULL;
   char *tok;
   int i = 0;

   while (envp[i] != 0) {
     printf("envp[%d] = %s", envp[i]);
     temp = realloc(temp, sizeof(envp[i]));
     strcpy(temp, envp[i]);
     tok = strtok(temp, "=");
     while (tok!=NULL){
         name = realloc(name, sizeof(tok));
         strcpy(name, tok);
         tok = strtok(NULL, "=");
         value = realloc(value, sizeof(tok));
         strcpy(value, tok);
         printf("Name = %s, value = %s", name, value);
     }
     change_var(name, value);
     i++;
  }
} 
4

1 回答 1

0

我可以建议一种不同的、更标准的打印方式吗?

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

extern char **environ; /* this is an external variable provided by the environment */

int main()
{
    char** env_ptr; /* declare a char** pointer that we will use to iterate through 'environ' */

    char* ptr = 0; /* this is used as a helper variable to store what 'strtok' returns */

    /* while the current string pointed to by *env_variable is not empty, increment it. */
    for (env_ptr = environ; *env_ptr != NULL; env_ptr++)
    {
        int i = 0; /* this is a control variable that is used to separate the left from the right part (divided by '=') */

        char temp[255] = ""; /* temporary string that will hold the whole current environment variable */

        strcpy(temp, *env_ptr);

        ptr = strtok(temp, "="); /* we specify the delimiters here, 'ptr' first points to the left part */

        char temp_a[255]; /* these two strings will hold the left and the right part respectively*/
        char temp_b[255];

        while (ptr != NULL) 
        {            
            if (i == 0) /* in the first iteration we get the left part so we store it */
                strcpy(temp_a, ptr);

            if (i == 1) /* in the second iteration we get the right part so we store it */
                strcpy(temp_b, ptr);

            ptr = strtok(NULL, "="); /* set 'ptr' to point to the right part,
                                        if this is already the second iteration,
                                        it will point to NULL */

            i++;
        }

        printf("%s - %s\n", temp_a, temp_b); /* you can assign temp_a and temp_b to anything you like */

    }

    return 0;
}

编辑:代码已更新,我没有您严格的详细信息,但您可以将其分配temp_atemp_b其成员字段

输出如下所示:

$ ./a.out 
LC_PAPER - en_US.UTF-8
LC_ADDRESS - en_US.UTF-8
SSH_AGENT_PID - 1311
LC_MONETARY - en_US.UTF-8
GPG_AGENT_INFO - /tmp/keyring-YUiDNO/gpg:0:1
TERM - xterm
SHELL - /bin/bash
于 2013-06-01T14:50:42.767 回答