#2
by かずま » 6年前
yopi さんが書きました: ↑6年前
取り急ぎ、文字列を配列に入れる方法を教えていただきたいです。
文字列のアドレスだけを配列に入れるやり方。
コード:
#include <stdio.h>
char *data[] = { "abc", "def", "ghi", "def" };
int ndata = sizeof(data) / sizeof(data[0]);
int idata = 0;
char *getStr() { return idata < ndata ? data[idata++] : NULL; }
#define SIZE 20 // 配列のサイズ
int main(void)
{
char *a[SIZE], *p;
int n;
for (n = 0; n < SIZE && (p = getStr()) != NULL; n++)
a[n] = p; // getStr で取得した文字列を配列 a に代入
for (int i = 0; i < n; i++) // 確認用
printf("%d: %s\n", i, a[i]); // 配列 a の内容を表示
}
文字列のコピーを配列に入れる方法。
コード:
#include <stdio.h>
#include <string.h> // strcpy
char *data[] = { "abc", "def", "ghi", "def" };
int ndata = sizeof(data) / sizeof(data[0]);
int index = 0;
char *getStr() { return index < ndata ? data[index++] : NULL; }
#define SIZE 20 // 配列のサイズ
#define LEN 64 // 文字列の最大長 + 1
int main(void)
{
char a[SIZE][LEN], *p;
int n;
for (n = 0; n < SIZE && (p = getStr()) != NULL; n++)
strcpy(a[n], p); // getStr で取得した文字列を配列 a にコピー
for (int i = 0; i < n; i++) // 確認用
printf("%d: %s\n", i, a[i]); // 配列 a の内容を表示
}
以上の 2つの方法を試してみて、どちらが希望するものかを教えてください。
また、setup で設定する「データの列」と、
getStr で取り出す「文字列」の関係はどうなっているのですか?
具体例で示してください。
[quote=yopi post_id=153982 time=1564654200]
取り急ぎ、文字列を配列に入れる方法を教えていただきたいです。
[/quote]
文字列のアドレスだけを配列に入れるやり方。
[code]
#include <stdio.h>
char *data[] = { "abc", "def", "ghi", "def" };
int ndata = sizeof(data) / sizeof(data[0]);
int idata = 0;
char *getStr() { return idata < ndata ? data[idata++] : NULL; }
#define SIZE 20 // 配列のサイズ
int main(void)
{
char *a[SIZE], *p;
int n;
for (n = 0; n < SIZE && (p = getStr()) != NULL; n++)
a[n] = p; // getStr で取得した文字列を配列 a に代入
for (int i = 0; i < n; i++) // 確認用
printf("%d: %s\n", i, a[i]); // 配列 a の内容を表示
}
[/code]
文字列のコピーを配列に入れる方法。
[code]
#include <stdio.h>
#include <string.h> // strcpy
char *data[] = { "abc", "def", "ghi", "def" };
int ndata = sizeof(data) / sizeof(data[0]);
int index = 0;
char *getStr() { return index < ndata ? data[index++] : NULL; }
#define SIZE 20 // 配列のサイズ
#define LEN 64 // 文字列の最大長 + 1
int main(void)
{
char a[SIZE][LEN], *p;
int n;
for (n = 0; n < SIZE && (p = getStr()) != NULL; n++)
strcpy(a[n], p); // getStr で取得した文字列を配列 a にコピー
for (int i = 0; i < n; i++) // 確認用
printf("%d: %s\n", i, a[i]); // 配列 a の内容を表示
}
[/code]
以上の 2つの方法を試してみて、どちらが希望するものかを教えてください。
また、setup で設定する「データの列」と、
getStr で取り出す「文字列」の関係はどうなっているのですか?
具体例で示してください。