首页 > 解决方案 > 即使在调试过程中看起来正确,也无法打印字符串

问题描述

我一直在尝试编写一个程序,它将字符串中的所有字母替换为它们在字母表中的位置。我想出了一个代码,它似乎在调试期间工作,但由于某种原因它不会打印结果字符串。

在调试过程中 main 中的字符串变量似乎是正确的,但它仍然不会打印。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>


char *alphabet_position(char *text) {
    char string[100] = {};
    char temp_c[5] = {};

    int i, temp_i;
    for (i=0; i<strlen(text); i++){
       if (text[i] >= 65 && text[i] <= 90){
                temp_i = text[i] - 'A' + 1;
                snprintf(temp_c, 4, "%d ", temp_i);
                strcat(string, temp_c);


            }
            if (text[i] >= 97 && text[i] <= 122){
                temp_i = text[i] - 'a' + 1 ;
                snprintf(temp_c, 4, "%d ", temp_i);
                strcat(string, temp_c);

            }

        }

return string;



}
int main()
{
    char *string = "The sunset sets at twelve o' clock.";
    char *temp = alphabet_position(string);
    printf("%s" ,temp);
    return 0;
}

另外,我真的不明白为什么在 strcat 调用期间使用 char *string 而不是 char string[100] 会导致分段错误。

标签: cc-strings

解决方案


推荐阅读