为什么打印出 char 数组会产生随机字符?

Why does printing out an array of char result in random characters?

我正在尝试学习编程,并且正在做一些随机的问题和任务。任务是写出字符串的最后三个字符,这就是我想出的。请不要为我解决这个问题,我问的是我的 output/result 不是让任何人为我解决问题:

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

int func(char *input_1, char *input_2) {
    char last_three_digits_1[3]; // define two arrays that hold the last three characters
    char last_three_digits_2[3];

    int x = 0;
    for(int y = strlen(input_1) - 4; y < strlen(input_1) - 1; y++) {
        last_three_digits_1[x] = input_1[i];
        x++;
    }

    x = 0; // repeat for the second string
    for(int z = strlen(input_2) - 4; z < strlen(input_2) - 1; z++) {
        last_three_digits_2[x] = input_2[i];
        x++;
    }


    printf("last3_1: %s, \nlast3_2: %s\n", last_three1, last_three2); // this seem to access random memory because it outputs "abc" followed by random "-???" or "-????" or "-?2?2". Same for the second array.

    return 0;
}

int main(int argc, char * argv[] ) {
    if(argc == 3) { // needs to be two strings. E.g: "abcd efghi"
        if(strlen(argv[1]) >= 3 || strlen(argv[2]) >= 3) { // if any of the strings are less than 3 in length, e.g. "ab wadnkwa" then do not proceed.
            func(argv[1], argv[2]); // send the user input to the function
        }

        return 0; // maybe redundant
    }

    return 0; // return 0 for failure
}
char last_three1[3]; // define two arrays that hold the last three characters
char last_three2[3];

您需要 space 来保存 [=12=] 个字符,因为 %s 期望 char*[=12=] 终止。

char last_three1[4]; 
char last_three2[4];

….
last_three1[x] = '[=11=]';
x = 0; // repeat for the second string
for(int i = strlen(text2) - 4; i < strlen(text2) - 1; i++) {
    last_three2[x] = text2[i];
    x++;
}
last_three2[x] = '[=11=]';

C 中的字符串以单个零字节结束。

您没有以零终止字符串,所以 printf 不知道在哪里停止打印(您很幸运您的程序没有彻底崩溃)。

我会重构这样的东西,所以你有一个函数,它只复制最后三个字节并以零结束字符串:

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

// out must be an array that can hold 4 bytes
// in must be >= 3 characters; otherwise this function returns non-zero
int get_last_three(char *out, const char *in) {
  int len = strlen(in);
  if (len < 3)
    return -1;
  for (int i = len - 3; i < len; i++) {
    *out = in[i];
    out++;
  }
  *out = 0; // Zero-terminate
  return 0;
}

int main(int argc, char *argv[]) {
  char out[4];
  for (int i = 1; i < argc; i++) {
    if (get_last_three(out, argv[i]) == 0) {
      printf("last3_%d: %s\n", i, out);
    }
  }
}

if语句中的条件

if(strlen(argv[1]) >= 3 || strlen(argv[2]) >= 3)

表示其中一个字符串的长度可以小于 3。在这种情况下,函数 func 可以调用未定义的行为。

你的意思好像是

if(strlen(argv[1]) >= 3 && strlen(argv[2]) >= 3)

否则你需要在函数func中检查字符串的长度是否大于或等于3,然后再输出最后三个字符。

如果一个字符串只有三个字符,那么例如在这个循环中

for(int i = strlen(text1) - 4; i < strlen(text1) - 1; i++)

变量 i 可以有一个实现定义的值,例如 -1,因此这个表达式 text1[i] 调用未定义的行为。

函数的return类型int没有意义。

请注意,如果您使用 %s 格式输出字符数组,则使用 printf 则该数组应包含一个字符串,该字符串是一个以零字符 [ 结尾的字符序列=24=].

所以 main 中的 if 语句和函数本身都没有意义。

要输出字符串的最后三个(或任何其他数字)字符,无需创建辅助数组。它可以做得更简单。

例如

void func( const char *text1, const char *text2, size_t n )
{
    size_t n1 = strlen( text1 );
   
    if ( !( n1 < n ) ) text1 += n1 - n;

    size_t n2 = strlen( text2 );

    if ( !( n2 < n ) ) text2 += n2 - n;

    printf( "last%zu_1: %s, \nlast%zu_2: %s\n", n, text1, n, text2 );
}

而且函数可以这样调用

func( argv[1], argv[2], 3 );

使用这样的函数声明,您可以输出两个字符串的任意数量的最后一个字符。还要考虑到函数参数具有限定符 const 因为传递的字符串在函数内不会更改。

这是一个演示程序

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

void func( const char *text1, const char *text2, size_t n )
{
    size_t n1 = strlen( text1 );

    if (!( n1 < n )) text1 += n1 - n;

    size_t n2 = strlen( text2 );

    if (!( n2 < n )) text2 += n2 - n;

    printf( "last%zu_1: %s, \nlast%zu_2: %s\n", n, text1, n, text2 );
}

int main( void )
{
    func( "Hello", "World", 3 );
}

程序输出为

last3_1: llo,
last3_2: rld