Y
Y
Yuri Kulaxyz2020-06-28 12:39:24
C++ / C#
Yuri Kulaxyz, 2020-06-28 12:39:24

How to copy the value of an environment variable through a pointer in SI?

Hello! The task is to display environment variables whose names are shorter than the specified number. To do this, I break each variable into [name, value] by the "=" symbol using strtok. However, strtok changes the value itself by adding NULL to the array. How can I copy the value of a variable in the "name = value" format to another variable, so that when working with the new one, the old one does not change. Tried with memcpy and didn't work.

void ShortNames(char **arr, int num) 
{
  printf("Значения переменных, у которых имена меньше заданного: \n");
  
  for (char **env = arr; *env != 0; env++)
  {
    char **result = malloc(sizeof(char*) * 1000);
    
    int size = sizeof(env);
        
    char* thisEnv = *env;
    //char* thisEnv = malloc(sizeof(char*) * size);
    //memcpy(thisEnv, *env, sizeof(char*) * size);
    
    split(result, thisEnv, "=");
  
  
    if (strlen(result[0]) <= num)
    {
      printf("%s \n", *env);
    }
  }
}


At the moment, this code prints only the names of environment variables and changes all environment variables in general.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2020-06-28
@Kulaxyz

How to copy value

To do this, you need to understand the structure of the data. The structure of the environment variables is as follows: there is a character array containing the text of all variables, and there is an array of pointers containing pointers to the beginning of each variable in the first array. Copying pointers from the second array but not copying the variables themselves is useless.
On the other hand, there is no need to copy anything in this task at all. And you don't need to use strtok either. You need to find the length of variable names. You can do it like this:
#include <string.h>

void ShortNames(char **arr, int num)
{
    int i;
    for (i = 0; arr[i]; ++i) {
        int len = strchr(arr[i], '=') - arr[i];
        if (len <= num)
            printf("%.*s\n", len, arr[i]);
    }
}

C
CityCat4, 2020-06-28
@CityCat4

Why the hell do you need strtok()? environment variable is just a string. What prevents you from finding the '=' sign through strchr(), counting one and taking strlen() from this point? So we got the length :)
(for universality of the code, you can check the character following the = on isspace(), if it matches, skip it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question