質問

I have a question, that sounds really stupid but i just don't get it. I try to program a small shell using following Struct for a list:

struct shellvalue {
    char* word;
    char isorder;
    char isarg;
    char ispipe;
    char isamp;
    unsigned int wordcount;
    unsigned int ordercount;
    struct shellvalue* next;
};

I initiate two pointers in the main-method with

struct shellvalue* start;
struct shellvalue* current;

Then i allocate now memory for the first element with:

void addtoken(char* word, int counter, struct shellvalue* start,
    struct shellvalue* current)
{
  if (counter == 0)
  { //creating first element
    size_t structsize = sizeof(struct shellvalue);
    struct shellvalue* tmp = (struct shellvalue*) malloc(structsize);
    tmp->word = malloc(strlen(word) + 1);
    strcpy(tmp->word, word);
    start = tmp;
    start->next = NULL;
    current = start;
  }
  else
  { // append new element
    struct shellvalue* new = (struct shellvalue*) malloc(
        sizeof(struct shellvalue));
    new->word = malloc(strlen(word) + 1);
    strcpy(new->word, word);
    current->next = new;
    current = new;
  }
}

But when i try to do

start = tmp;

I can see in the debugger, that start has still the value NULL from the main-Method. Both pointers seem of the same type to me and i get no warnigs or anything with this compilertags

-Wall -ansi -Wconversion -pedantic -m64

I really don't see, what i do wrong.

役に立ちましたか?

解決

Your assignment start = tmp only changes the value of start inside addtoken(). Since pointers are passed by value, this doesn't alter the pointer start outside of your function. In order to achieve this, you have to pass a pointer to pointer into your function:

void addtoken(char* word, int counter, struct shellvalue** start, struct shellvalue** current) {
    // ..
    // replace assignments to start/current with:
    *start = tmp
    // ..
}

Then, when invoking your function:

struct shellvalue* start;
struct shellvalue* current;

addToken(word, counter, &start, &current);

My suggested alternative:

Use a struct to hold both of your pointers, and pass a pointer to it into your function:

struct shellvalue_list {
    struct shellvalue* start;
    struct shellvalue* end;
};

void addtoken(struct shellvalue_list* list, char* word, int counter) {
    // ..
    list->start = tmp;
    // ..
}

This is a common idiom for object-oriented code in C.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top