C - Копирование массива строк в структуру - PullRequest
0 голосов
/ 16 сентября 2018

Вот уже пару часов я бьюсь головой об стену.

У меня есть структура, определенная следующим образом:

typedef struct historyNode {
    int pos;
    char cmd[MAXLINE];
    char* args[(MAXLINE / 2) + 1];
    struct historyNode* next;
} historyNode_t;

Я пытаюсь скопироватьпереданный массив строк в поле args в приведенной выше структуре.Это происходит в следующем методе:

void addToHistory(history_t* history, char* args[(MAXLINE / 2) + 1]) {
    historyNode_t* node = malloc(sizeof(historyNode_t));

    ...

    int index = 0;
    while (args[index] != NULL) {
        node->args[index] = args[index];

    ...

Когда я пытаюсь получить доступ к значению args этого узла в более позднее время вне метода, он выплевывает значение, равное тому, что находится в переданном входе.args массив в этот момент;то есть значения на самом деле не копируются, а скорее адреса.

Я чувствую, что это просто, но меня это расстраивает.Любые советы о том, как это можно исправить, очень ценятся.

Ответы [ 2 ]

0 голосов
/ 16 сентября 2018

В C, C ++,

char   charA[10];        // Array of char (i.e., string) up to 9+1 byte
                         // 10 bytes of memory is reserved

char  *string;           // Pointer to a null-terminated string
                         // Memory for 1 pointer (4 or 8 bytes) are reserved
                         // Need to allocate arbitrary bytes of memory
                         // Up to programmer to interpret the memory structure
                         // E.g.,
                         //   As array of pointers to string
                         //   A long string 
                         //   etc.
                         // This pointer could be passed to other functions
                         // and content at that pointed address could be changed

//char  *strings[];      // Cannot declare pointer to unknown length of array
                         // Use char** as below

char **ptrs2Strings;     // Pointer to pointer to char
                         // Memory for 1 pointer (4 or 8 bytes) are reserved
                         // Need to allocate arbitrary bytes of memory 
                         // Up to programmer to interpret the memory structure
                         // E.g.,
                         //   As array of pointers to string
                         //   A long string 
                         //   etc.
                         // The pointer to pointer could be passed to other 
                         // functions. The content at that pointed address is
                         // only an address to an user-allocated memory.
                         // These functions could change this second address as
                         // well as content of the memory pointed by the second
                         // address.

char  *charvar[10];      // array of 10 char pointers
                         // Memory for 10 pointers (40 or 80 bytes) are reserved
                         // Programmer could  allocate arbitrary bytes of memory 
                         // for each char pointer

char   stringA[10][256]; // array of 10 strings, and each string could store 
                         //   up to 255+1 bytes

Надеюсь, это поможет вам.

0 голосов
/ 16 сентября 2018

Я пытаюсь получить доступ к значению args этого узла позднее, вне метода

Для этого вы должны были вернуть указатель на struct historyNode везде, где вы пытаетесь получить доступ к значению args. Вот пример для этого:

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

 struct node
 {
     char *a[2];
 };

 struct node *fun()
 {
     char *c[]={"hello","World"};
     struct node *ptr= malloc(sizeof(struct node));
     ptr->a[0]=c[0];
     ptr->a[1]=c[1];
     return ptr;
 }

 int main()
 {
     struct node *ptr=fun();
     printf("%s %s\n",ptr->a[0],ptr->a[1]);
     return 0;
 }

ВЫХОД: hello World

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...