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;
}