Указатель на функцию, получающую ошибку "должен быть изменяемым"

У меня есть небольшая проблема - по какой-то причине, когда я пытаюсь перераспределить память на указатель на указатель структуры, чтобы увеличить количество блоков памяти на один для дополнительной структуры в функции, Intellisense говорит мне, что "выражение должно быть изменяемое значение ". Дело в том, если я попытаюсь выделить input само по себе все нормально - проблема в том, когда я пытаюсь перераспределить input + 1,

Структуры в использовании:

struct Entry_t
{
    char *word;
    Year **years;
    char **syn;
    Meaning **mean;
    Entry *next;
};

struct Mean_t
{
    char *word;
    Entry **enword;
    Meaning *next;
};

Функции:

/*
| Function: IsInMean
| Action: Checks whether the meaning already exists
| Input: Master meaning struct, the string
| Returns: The address of the necessary place if yes, NULL otherwise
*/
Meaning *IsInMean(Meaning *MEANS, char *str)
{
    if(MEANS)
    {
        if(strcmp(MEANS->word,str) == 0)
            return MEANS;
        else
            return IsInMean(MEANS + 1,str);
    }
    else
        return MEANS;
}

/*
| Function: FindMeanPlace
| Action: Checks where to wedge the meaning.
| Input: The master Meanings dictionary, the string
| Returns: The address of the place where to wedge, NULL if all are bigger.
*/
Meaning *FindMeanPlace(Meaning *MEANS, char *str)
{
    int cmp;
    if((cmp = strcmp(MEANS->word,str)) > 0)
        return NULL;
    else if(cmp < 0 && strcmp(MEANS->next->word,str) > 0)
        return MEANS;
    else
        return FindMeanPlace(MEANS + 1,str);
}

/*
| Function: NewMean
| Action: Creates and initializes a new meaning struct
| and places in it a new entry
| Input: Standard input, new entry, string with the meaning
| Returns: The address of the new meaning struct
*/
Meaning *NewMean(STANDARD_INPUT,Entry *new_e, char *str)
{
    Meaning *temp = (Meaning*)malloc(sizeof(Meaning));
    InitMean(temp);
    temp->word = (char*)calloc(strlen(str) + 1,sizeof(char));
    strcpy(temp->word,str);
    *(temp->enword) = new_e;
    return temp;
}

/*
| Function: SetMean
| Action: Sets the meanings field of an entry
| Input: Standard input, address of the new entry and
| the appropriate sub-string
| Returns: nada
*/
void SetMean(STANDARD_INPUT, Entry *new_e, char *str)
{
    char *cutout, delim[] = ",_";
    char **temp = NULL;
    int len = 0, cmp, index;
    Entry **entemp, *etemp;
    Meaning *input, *mtemp;
    cutout = strtok(str,delim);
    while(cutout)
    {
        temp = (char**)realloc(temp,(len + 1)*sizeof(char*));
        if(!temp)
            Pexit(STANDARD_C);
        *temp = (char*)calloc(strlen(cutout) + 1,sizeof(char));
        if(!(*temp))
            Pexit(STANDARD_C);
        strcpy(*temp,cutout);
        temp++;
        len++;
        cutout = strtok(NULL,delim);
    }
    QsortCust(STANDARD_C,temp,len + 1);
    while(temp)
    {
        index = 0;
        if(input = IsInMean(MEANS,*temp))
        {
            entemp = input->enword;
            if(strcmp(entemp[0]->word,new_e->word) > 0)
                //entemp + 1 = (Entry**)realloc(entemp,sizeof(entemp) + sizeof(Entry*));  "expression must be modifiable lvalue"
            while(entemp + index)
            {
                if((cmp = strcmp((entemp[index])->word,new_e->word)) < 0 && strcmp((entemp[index + 1])->word,new_e->word) > 0)
                {
                    //(entemp + index + 1) = (Entry**)realloc(entemp + index,sizeof(entemp + index) + sizeof(Entry*));  "expression must be modifiable lvalue"
                    //if(!(entemp + index + 1))
                    //  Pexit(STANDARD_C);
                }
                else if(cmp <0)
                {
                    index++;
                }
            }
        }
        else
        {
            input = FindMeanPlace(MEANS,*temp);
            mtemp  = input->next;
            input->next = NewMean(STANDARD_C,new_e,*temp);
        }
    }
}

STANDARD_INPUT определяется как основной словарь (первая запись *), годовой словарь (первый год *) и словарь значений (первое значение *). STANDARD_C определяется как имена переменных из стандартного ввода.

1 ответ

Решение

Если то, что вы хотите сделать (по комментариям), это увеличить допинг-вектор entemp само по себе, но добавив новое место в начало вместо конца, вы не можете сделать это с помощью одной операции. realloc всегда должен передаваться указатель без смещения, полученный от malloc (или же calloc или предыдущий звонок realloc), и это всегда добавляет пробел в конце. Вы должны скользить все вниз, используя memmove, Например:

nelements += 1;
entemp = realloc(entemp, nelements * sizeof(Entry *));
assert(entemp);
memmove(entemp, entemp+1, (nelements - 1) * sizeof(Entry *));

Кроме того, как я только что заметил это: sizeof(entemp) не возвращает размер выделения блока памяти, на который указывает entemp, Возвращает размер самого указателя. Нет способа получить размер выделения блоков в куче C; Вы должны отслеживать их самостоятельно. Это то, что мой nelements Переменная, выше.

Тесно связанный обязательный тангенциальный комментарий: не приводите возвращаемое значение reallocтак же, как вы не разыгрываете возвращаемое значение malloc или же calloc, Это не просто стиль: кастинг, когда вам не нужно, может скрывать ошибки!

Менее тесно связанный, но все же обязательный стиль придирки: NAMES_IN_ALL_CAPS по давней договоренности зарезервированы для констант. Не используйте их для имен переменных. И ваши магические макросы, которые расширяются до целых объявлений переменных / аргументов, являются правильными.

Другие вопросы по тегам