0

Я новичок на Си и пытаюсь создать аналог словоря, и столкнулся с проблемой типизации. Мой словарь умеет создовать ключ-значение только для const char, я захотел расширить программу, что бы она могла так же использовать значения и других типов данных, попробовал использовать указатель на void, но проблема осталась и у меня появилось несколько вопросов:

Можно ли сделать так что бы функция преобразовывала в словарь разные типы данных?

Как я могу это сделать?

Основной код:

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

#define MAXSIZE 5000

struct base
{
    uint8_t *up;
    uint8_t size;
};

typedef struct
{
    base key[MAXSIZE];
    base data[MAXSIZE];
    uint8_t index;
} dict_t;

static uint8_t sizeVal (const char *val);

static dict_t *init (uint8_t s_key, uint8_t s_data)
{
    dict_t *dict;

    dict = (dict_t *) malloc(sizeof(dict_t));
    dict -> key -> up = (uint8_t *) malloc(s_key);
    dict -> data -> up = (uint8_t *) malloc(s_data);

    dict -> key -> size = s_key;
    dict -> data -> size = s_data;
    dict -> index = 1;

    return dict;
}

dict_t *newDict (const char *key, const char *data)
{
    dict_t *dict;
    uint8_t s_key;
    uint8_t s_data;

    s_key = sizeVal(key);
    s_data = sizeVal(data);

    dict = init(s_key, s_data);

    memcpy(dict -> key, key, s_key);
    memcpy(dict -> data, data, s_data);

    return dict;
}

void printDict (dict_t *dict)
{
    for (int i = 0; i < dict -> index; i++)
    {
        fwrite(dict -> key, sizeof(uint8_t), dict -> key -> size, stdout);
        fwrite(": ", sizeof(char), 2, stdout);
        fwrite(dict -> data, sizeof(uint8_t), dict -> data -> size, stdout);
    }
}

static uint8_t sizeVal (const char *val)
{
    uint8_t size;

    for (size = 0; *val != '\0'; val++)
    {
        size++;
    }

    return size;
}

Функция main:

#include "dict.c"

int main ()
{
    dict_t *dict;

    dict = newDict("key", "data\n");
    printDict(dict);

    return 0;
}

Заранее спасибо.

1 ответ 1

1

Разные типы в список можно положить только по указателю с указателем номера типа элемента.

struct baseString
{
    uint8_t *up;
    uint8_t size;
};

struct baseDoubleVector
{
    double * up ;
    uint8_t size ;
} ;

enum { TypeString , TypeDoubleVector } ;

typedef struct {
  void * ptr ;
  int type ;
} virtualBase ;

typedef struct
{
    base key[MAXSIZE];
    virtualBase data [ MAXSIZE ] ;
    uint8_t index;
} dict_t ;

Нужно будет писать на каждый тип свои функции добавления. А для удобства использования можно попробовать _Generic. (Аналог функции с одним названием , но с разными типами.)

Или в шаблонном стиле так :

# define AddDict( T ) AddDict_##T

dict_t * AddDict ( baseString ) ( const char *key , baseString * ) ;
dict_t * AddDict ( baseDoubleVector ) ( const char *key , baseDoubleVector * ) ;
3
  • Спасибо большое, только у меня ещё один очень глупый вопрос, как я могу определять к какому типу данных относится входной элемент, заранее спасибо.
    – Gari
    22 янв 2020 в 16:58
  • поле type - непонято ?
    – AlexGlebe
    22 янв 2020 в 16:59
  • А всё наконец то дошло, большое спасибо, что объяснили.
    – Gari
    22 янв 2020 в 17:02

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.