0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

データ型とサイズを出力するプログラム

Last updated at Posted at 2024-11-30

学習用にデータ型とサイズを出力するプログラムを作ってみました。

print_size_of_data_types.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

// main()に置いたハッシュテーブルのための構造体
typedef struct dataType
{
    char    *data_name;
    size_t  data_size;
    size_t  data_align;
} DT;

int print_size_of_data_types(DT *types)
{
    int ret;

    for (int i = 0; types[i].data_name != NULL; i++)
    {
        ret = printf("%s: %zu bytes, alignment: %zu bytes\n",\
        types[i].data_name, types[i].data_size, types[i].data_align);
        // printf()にエラーが起きた場合
        if (ret < 0)
            return -1;
    }
    return 0;
}

int main()
{
    // データ型の名前とサイズとアライメント(照準、配置)を収納したハッシュテーブル
    DT types[] = {
        {"\t int", sizeof(int), _Alignof(int)},
        {"unsigned int", sizeof(unsigned), _Alignof(unsigned)},
        {"\t long", sizeof(long), _Alignof(long)},
        {"unsigned long", sizeof(unsigned long), _Alignof(unsigned long)},
        {"\t long long", sizeof(long long), _Alignof(long long)},
        {"unsigned long long", sizeof(unsigned long long), _Alignof(unsigned long long)},
        {" short", sizeof(short), _Alignof(short)},
        {" float", sizeof(float), _Alignof(float)},
        {"double", sizeof(double), _Alignof(double)},
        {"  bool", sizeof(bool), _Alignof(bool)},
        {"char  ", sizeof(char), _Alignof(char)},
        {"char* ", sizeof(char*), _Alignof(char*)},
        {"char**", sizeof(char**), _Alignof(char**)},
        {" size_t", sizeof(size_t), _Alignof(size_t)},
        {"ssize_t", sizeof(ssize_t), _Alignof(ssize_t)},
        {NULL, 0, 0} // Sentinel value 番兵ノードとして機能
    };

    return print_size_of_data_types(types);
}

同じくC言語学習中の方々に役立ててもらえたら。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?