c不正确输出中的反向字符串



我正在编写一个程序来扭转C中的字符串,而我的代码是:

#include<stdio.h>
#include<string.h>
void main()
{
    int sz;
    printf("Enter the size of the string : ");
    scanf("%d",&sz);
    char str[sz];
    gets(str);
    printf("Enter the string : n");
    gets(str);
    char str1[sz];
    int i =0;
    --sz;
    for(i=0;i<=sz;i++)    
    {
          str1[sz-i]=str[i];
    }
    printf("%s",str1);
}

这个程序为字符串尺寸8,9和10提供了怪异的输出对于8号尺寸,将打印的反向字符串随后是一个空间和2个垃圾字符,对于9尺寸,反向字符串被打印,后面是2个垃圾字符,对于10号尺寸,相反的字符串正在由垃圾字符打印,而对于其他字符串大小的程序正常运行。为什么会发生?

注意:

  • 尝试通过询问用户来限制输入字符串并不聪明,用户仍然可以编写长度/更少
  • 的字符串
  • 从控制台读取字符串默认情况下不允许空格

第一个选项:
读取静态大小的字符串:

 char original[5];
 scanf("%5s", original); // String containing 5 chars

第二个选项:
读取可变大小的字符串:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
// Length of String
unsigned expected;
printf("Enter the length of the string: ");
scanf("%u", &expected);
char *temp; // Warning: Uninitialized
// Get string
printf("Enter the string: ");
scanf("%s", temp);
unsigned actual = strlen(temp);
unsigned length = actual > expected ? expected : actual;
char *string = (char *) malloc(length * sizeof(char));
char *reverse = (char *) malloc(length * sizeof(char));
 // Trim string to proper size
for (int i = 0; i < length; i++) {
  string[i] = temp[i];
}
// Reverse string
for (int i = 0, j = length - 1; i <= j; i++) {
  reverse[i] = string[j - i];
}
// Print Strings
printf("%s", string);
printf("n%s", reverse);

最新更新