распечатать строку в C - PullRequest
       8

распечатать строку в C

1 голос
/ 23 января 2011

Я на начальном уровне в языке программирования C. Я пытаюсь распечатать строку, указатель которой передается из функции в другую переменную-указатель в функции main (). Мои знания очень ограничены в C, и я посмотрел в Интернете (возможно, я не смотрел достаточно глубоко, но, пожалуйста, помогите) вот код:

int i;
char *result;
result= center_string("I go to school everyday\nto study");

i=0;
while (result[i]!='\0'){
    printf("%c\n", result[i]);
    i++;
}

и результат, который я получил, - это 4 странных символа, расположенных вертикально (к сожалению, stackoverflow.com не позволяет мне публиковать картинку)

пожалуйста, помогите! заранее спасибо

- добавлено --- это код для center_string:

static char* center_string(char* msg){
char toReturn[34]; // the return message has to contain two lines in one. It might be better to form this string while traversing two strings, rather than forming by the union of two lines
char centerString[34];

// padding can be done during the process of splitting two lines or after.
// it's harder to do while splitting two lines because the length of each line is unknown
// countSecond starts with -1 because it contains \n which should not be in it. So this number will be discarded
int paddingFirst = 0, paddingSecond = 0, countFirst = 0, countSecond = -1, countReturn = 0; // maximum number of return string is 34

// stillOnTheFirstLine is a boolean variable but representing by a integer with 1 digit
int i = 0, stillOnTheFirstLine = 0; // start counting the character in the second line 

 //initialize the return line
for (i=0; i<34; i++){
    toReturn[i] = '\0';
    centerString[i] = '\0';
    // printf("initializing toReturn[%i] with value %c\n",i, toReturn[i]);
}

i = 0;

while ( msg[i]!='\0' ) {
    // getting the first line to display
    // the limit is 16 chars or \n to the second line
    // i.e: I go to school e|very day\nto study
    // firstLine = "I go to school e"
    // secondLine ="to study"
    // discarded = "very day"
    // get the first line
    if (i<=15 && msg[i]!='\n'){
        // this is the first line
        // insert the character into the return string
        toReturn[countReturn] = msg[i];
        //printf("First line: %c\n", toReturn[countReturn]);
        countReturn++;
        countFirst++;
    }else{
        // when the first line is finished
        // there are two cases
        // first case: when the first line is longer than 16 character long
        if (msg[i]!='\n' && i>15 && stillOnTheFirstLine==0){
            // discard the character
            //printf("Discard: %c\n", msg[i]);
        }else{
            stillOnTheFirstLine = 1; // yes the parser is still on the second line
            // this is the second case which the first line is finished
            // check for 16 character instead of 15 because one of them is \n which separate line 1 and 2
            if (countReturn<33 && stillOnTheFirstLine==1){ 
                toReturn[countReturn] = msg[i]; // put the character from the msg string to the toReturn
                //printf("Second line: %c\n", toReturn[countReturn]);
                countReturn++;
                countSecond++;
            }
            // whatever after this is discarded 
        }
    }
    i++;
}

// start padding
paddingFirst = floor((double)(16-countFirst)/2);
paddingSecond = floor((double)(16-countSecond)/2);

// padding the first line
i=0;
while (toReturn[i]!='\0' && toReturn[i]!='\n'){
    centerString[paddingFirst] = toReturn[i];
    paddingFirst++;
    i++;
}

// add '\n' into the centerString
centerString[paddingFirst] = toReturn[i];
// then continue with the next character in toReturn
i++;

// padding the second line
paddingSecond = i+paddingSecond;
while(toReturn[i]!='\0'){
    centerString[paddingSecond] = toReturn[i];
    paddingSecond++;
    i++;
}


/*for(i=0; i<34; i++){
    printf("the result string is: %c\n", centerString[i]);
}*/
return centerString;

}

Ответы [ 4 ]

2 голосов
/ 23 января 2011

Вы возвращаете centerString из center_string. Однако centerString объявлен как массив в стеке. Поэтому, когда возвращается center_string, хранилище для centerString больше не доступно.

У вас есть несколько вариантов:

  1. Вы можете выделить centerString в куче (используя malloc), но вы должны четко указать, что вызывающей стороне потребуется освободить хранилище, вызвав функцию, подобную make_center_string или new_center_string .

  2. Вы можете объявить centerString как static:

    static char centerString[34];
    

    Это заставляет centerString использовать пространство памяти, отличное от стека (аналогично глобальным переменным, но вы можете получить к нему доступ только непосредственно из функции center_string; но center_string может вернуть свой адрес другой функции) , Это позволит вам правильно вернуть centerString и использовать его в main.

2 голосов
/ 23 января 2011

Почему ты не можешь просто сделать printf("%s\n", result)

1 голос
/ 23 января 2011

Вы возвращаете буфер, выделенный в стеке center_string, и он больше не будет действителен после выхода из этой процедуры.

Я уверен, что есть другие проблемы, но я думаю, что сейчас это основная!

0 голосов
/ 23 января 2011

Вам необходимо сопоставить возвращаемую строку или взять указатель в качестве аргумента:

void center_string (char * msg, char * centerString)

и объявите centerString в том же методе, который вы вызываете center_string.

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