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?

More than 1 year has passed since last update.

c++ vector<string> と同等の処理をC言語の動的配列で実装する

Last updated at Posted at 2024-05-13
code_only.cpp
std::vector<string> str5(5);

これをC言語の動的配列で行う
Visual Studio 2022 を使用

普段ならこんな面倒でタイパの悪い事はする気ない(Z世代のマネしてみた)が、
それに挑戦してみたいという人がいたので協力してみた。

1命令事に調べると時間がかかるので良さそうなサンプルを探したところ、提示されている方がおられたのでありがたく使わせていただくことにした。

こちらのサイトのプログラムを改造してみて、code_only.cpp をC言語で実装するサンプル
※以下は、プロジェクトのプロパティ > C/C++ > SDLチェック いいえ(/SDL-) にしないと動作しません

c_vecor.cpp
// std::vector<string> str5(5);

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

int main()
{
    char** a;
    unsigned v = 5, h = 20; // 配列5個
    unsigned i, j;

    a = (char**)calloc(v, sizeof(char*));
    for (i = 0; i < v; i++) {
 //       a[i] = nullptr;  // ワーニング消せなかった
        a[i] = (char*)calloc(h, sizeof(char));  // ワーニング消せなかった
    }

    const char* str[] = {"apple","banana","orange","pineapple","mango"}; // テストデータ
    for (i = 0; i < v; i++) 
    {
            strcpy(a[i],str[i]);
    }
    for (i = 0; i < v; i++) 
    {
            printf("%s\n",a[i]);
    }

    for (i = 0; i < v; i++) {
        free(a[i]);
    }
    free(a);

    return 0;
}

実行結果

apple
banana
orange
pineapple
mango


参考サイトが有るにも関わらず、伝えないのはありえないと思う。
参考にしたサイトが有れば必ず書きましょう。

C++のありがたみを実感できる形になった。
こんな面倒なことは普通はやらない。

しかし、きまぐれが起きたら、またやるかも知れない。

==== 追記 ====
ワーニング対策がこちらのサイトに書かれていました。
記事ではVisualStudio2019の対策
ワーニング消しに成功しました。

ワーニング対策コード(クリックで開きます)
c_vector.c
#include <stdio.h>
#include<stdlib.h>
#include <malloc.h>
#include <string>

int main()
{
    char** a;
    unsigned v = 5, h = 20;
    unsigned i, j;

    a = (char**)calloc(v, sizeof(char)*h);
    for (i = 0; i < v; i++) {
        if (a != nullptr)   // ワーニング消し
        {
            a[i] = (char*)calloc(h, sizeof(char));
        }
    }

    const char* str[] = {"apple","banana","orange","pineapple","mango"}; // テストデータ

    for (i = 0; i < v; i++) 
    {
        if (a != nullptr && a[i]!=nullptr)   // ワーニング消し
        {
            strcpy(a[i],str[i]);
        }
    }

    for (i = 0; i < v; i++) 
    {
        if (a != nullptr)   // ワーニング消し
        {
            printf("%s\n",a[i]);
        }
    }

    for (i = 0; i < v; i++) {
        if (a != nullptr)   // ワーニング消し
        {
            free(a[i]);
        }
    }
    free(a);

    return 0;
}

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?