ページ 11

array initializer must be an initializer list or string

Posted: 2016年4月21日(木) 21:05
by hogged
c言語の勉強をしているのですが、コンパイラエラーが出ていまいます。原因が分からないのですが、何がいけないのでしょうか?
エラーメッセージの内容
033-2.c:18:7: error: array initializer must be an initializer list or string literal
char str[21] = S[0];

コード:

#include <stdio.h>

int main (void)
{
	int N, max, add;
	int i, j, k;
	char S[1001][21];
	int P[1001];
	scanf("%d", &N);

	for (i = 0; i < N; ++i)
	{
		scanf("%s", S[i]);
		scanf("%d", &P[i]);
	}

	max = P[0];
	char str[21] = S[0];

	for (j = 0; j < N; ++j)
	{
		if (P[i] < P[i + 1])
		{
			max = P[i + 1];
			str = S[i + 1];
		}
	}

	for (k = 0; k < N; ++k)
	{
		add += P[k];
	}

	if (max >= (add /2))
	{
		printf("%s\n", str);
	}else{
		printf("atcoder\n");
	}

	return 0;
}

Re: array initializer must be an initializer list or string

Posted: 2016年4月21日(木) 21:15
by box
hogged さんが書きました:

コード:

	char str[21] = S[0];
検証してないのでアレですが、たぶん、
#include <string.h>
を加えた上で、

コード:

    char str[21];
    strcpy(str, S[0]);
とかせねばならないのでしょう。

Re: array initializer must be an initializer list or string

Posted: 2016年4月21日(木) 21:39
by みけCAT
エラーメッセージの通り、初期化子リストでも文字列リテラルでもないもので配列を初期化しようとしているのがいけないのでしょう。

以下、N1570より引用
6.2.5 Types さんが書きました: 21 Arithmetic types and pointer types are collectively called scalar types. Array and
structure types are collectively called aggregate types.
6.7.9 Initialization さんが書きました: 14 An array of character type may be initialized by a character string literal or UTF −8 string
literal, optionally enclosed in braces. Successive bytes of the string literal (including the
terminating null character if there is room or if the array is of unknown size) initialize the
elements of the array.

(中略)

16 Otherwise, the initializer for an object that has aggregate or union type shall be a brace-
enclosed list of initializers for the elements or named members.

Re: array initializer must be an initializer list or string

Posted: 2016年4月21日(木) 22:27
by hogged
box さんが書きました:
hogged さんが書きました:

コード:

	char str[21] = S[0];
検証してないのでアレですが、たぶん、
#include <string.h>
を加えた上で、

コード:

    char str[21];
    strcpy(str, S[0]);
とかせねばならないのでしょう。

コード:

#include <stdio.h>
#include <string.h> //strcpyを利用するため

int main (void)
{
	int N, max, add;
	int i, j, k;
	char S[1001][21];
	int P[1001];
	scanf("%d", &N);

	for (i = 0; i < N; ++i)
	{
		scanf("%s", S[i]);
		scanf("%d", &P[i]);
	}

	max = P[0];
	char str[21];
	strcpy(str, S[0]);

	for (j = 0; j < N; ++j)
	{
		if (P[j] < P[j + 1])
		{
			max = P[j + 1];
			strcpy(str, S[j + 1]);
		}
	}

	for (k = 0; k < N; ++k)
	{
		add += P[k];
	}

	if (max > (add / 2))
	{
		printf("%s\n", str);
	}else{
		printf("atcoder\n");
	}

	return 0;
}
コンパイル可能になりました。 ありがとうございました。