Как исправить «строку инициализатора для массива символов слишком длинную» и «лишние элементы в инициализаторе массива символов» при настройке массива двумерных символов - PullRequest
0 голосов
/ 03 января 2019

Я пытаюсь создать двумерный массив, который будет хранить вопрос и ответ в каждой строке массива, что мне нужно сделать, чтобы настроить это, а также иметь возможность вызывать строки из этого массива.

Я попытался изменить скобки справа от имени массива (например, [15] [2], [15], без скобок) и рассмотрел несколько проблем, связанных с переполнением стека, которые не совсемработать для моей проблемы.Я также получаю сообщение об ошибке «подписанное значение не является ни массивом, ни указателем, ни вектором» в случае «H» оператора switch.Я также получаю несколько «скобок вокруг скалярного инициализатора», «лишние элементы в скалярном инициализаторе» и «делает целое число из указателя без предупреждений приведения [-Wint-преобразование]» во время загрузки.Я прошу прощения, если я допустил какие-либо очевидные ошибки, я прихожу на C из Python и все еще пытаюсь обернуть его вокруг.случай H и дайте мне очки, основываясь на том, сколько правильных ответов я получил.

Ответы [ 2 ]

0 голосов
/ 03 января 2019

Как и @usr, упомянутый в его Ответе, возможно, вам лучше использовать массив указателей для этой задачи.

Вот пример одного из ваших массивов:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

#define GETLEN(array) sizeof array / sizeof array[ 0 ]
const char *separator   ( const size_t num );

int main( void )
{
    const char *history[] =
    {
        "Which English king was \"mad\"?","George III",
        "Who started the Protestant Reformation?","Martin Luther",
        "Who was the first person to see the moons of Jupiter?","Galileo",
        "What Viking group settled in France before conquering England, Sicily, and Malta?","The Normans",
        "What group sacked Baghdad in 1258, ending the Islamic Golden Age?","The Mongols",
        "Against what city did Rome fight the Punic Wars?","Carthage",
        "What yellow gas was famously used in WWI?","Mustard Gas",
        "What epic poem is thought to be the oldest in the English language?","Beowulf",
        "What ancient empire was led by Xerxes, Cyrus, and Darius?","Persia",
        "Who was the most notorious member of the Ba'ath Party?","Saddam Hussein",
        "What Italian adventurer wrote about his 24 year journey from Venice to China and back?","Marco Polo",
        "What young pharaoh's tomb was discovered in 1922?","Tutankhamun",
        "Before becoming king of England, what country was James I the king of?","Scotland",
        "What was the primary language of the Byzantine Empire?","Greek",
        "For what crime was Al Capone convicted of in 1931?","Tax Evasion",
    };
    for ( size_t i = 0 ; i < GETLEN( history ) ; i++ )
    {
        printf("%s%s\n", separator(i), history[i] );
    }
}

const char *separator ( const size_t num )
{
    if ( num % 2 == 0 )
    {
        return "Question:\t";
    }
    return "Answer:\t\t";
}

Выход:

Question:   Which English king was "mad"?
Answer:     George III
Question:   Who started the Protestant Reformation?
Answer:     Martin Luther
Question:   Who was the first person to see the moons of Jupiter?
Answer:     Galileo
Question:   What Viking group settled in France before conquering England, Sicily, and Malta?
Answer:     The Normans
Question:   What group sacked Baghdad in 1258, ending the Islamic Golden Age?
Answer:     The Mongols
Question:   Against what city did Rome fight the Punic Wars?
Answer:     Carthage
Question:   What yellow gas was famously used in WWI?
Answer:     Mustard Gas
Question:   What epic poem is thought to be the oldest in the English language?
Answer:     Beowulf
Question:   What ancient empire was led by Xerxes, Cyrus, and Darius?
Answer:     Persia
Question:   Who was the most notorious member of the Ba'ath Party?
Answer:     Saddam Hussein
Question:   What Italian adventurer wrote about his 24 year journey from Venice to China and back?
Answer:     Marco Polo
Question:   What young pharaoh's tomb was discovered in 1922?
Answer:     Tutankhamun
Question:   Before becoming king of England, what country was James I the king of?
Answer:     Scotland
Question:   What was the primary language of the Byzantine Empire?
Answer:     Greek
Question:   For what crime was Al Capone convicted of in 1931?
Answer:     Tax Evasion
0 голосов
/ 03 января 2019

вы инициализируете массив char списком строковых литералов.Вам нужен массив указателей .

Например:

   char *history[15] = { "Which English king was \"mad\"?","George III",
                         "Who started the Protestant Reformation?","Martin Luther",
                         ...

И то же самое для других массивов.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...