C 字符数组打印额外的垃圾内存

C 字符数组打印额外的垃圾内存,c,C,这个程序应该输出VYGHBUTMDE,但它在末尾附加了一些垃圾字符。为什么会这样 #include <stdio.h> #include <string.h> int encrpypt(char ciphertext_buffer[], char plaintext[], char key[]) { int i; for (i=0; i<strlen(plaintext); i++) { ciphertext_buffer[i] = (char)

这个程序应该输出
VYGHBUTMDE
,但它在末尾附加了一些垃圾字符。为什么会这样

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

int
encrpypt(char ciphertext_buffer[], char plaintext[], char key[]) {
  int i;
  for (i=0; i<strlen(plaintext); i++) {
    ciphertext_buffer[i] = (char) ( ( ((int)plaintext[i] - 65 + (int)key[i%(strlen(key))] - 65) % 26 ) + 65 );
  }
  return 0;
}

int
main() {
  char ciphertext_buffer[10];
  encrpypt(ciphertext_buffer, "THISISCOOL", "CRYPT");
  printf("%s\n", ciphertext_buffer);
  return 0;
}
#包括
#包括
int
加密(字符密文缓冲区[],字符明文[],字符密钥[]){
int i;

对于(i=0;i),因为您只为一个10字节的字符串分配一个10字节的数组,对于终止的空字符来说“无处”。请考虑将缓冲区的大小增加到至少一个大于“可见”的字符串长度的字符。字符。

终止字符串时不能为空。这是一个稍微修改的版本:(尽管仍然存在问题)

#包括
#包括
int
加密(字符密文缓冲区[],字符明文[],字符密钥[]){
int i;

对于(i=0;i字符数组必须以“/0”结尾。因此,始终需要将字符数组分配为最大字符串大小+1

尝试下面的更正

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

int encrpypt(char ciphertext_buffer[], char plaintext[], char key[]) {
  int i;
  for (i=0; i<strlen(plaintext); i++) {
    ciphertext_buffer[i] = (char) ( ( ((int)plaintext[i] - 65 + (int)key[i%(strlen(key))] - 65) % 26 ) + 65 );
  }
 ciphertext_buffer[i] = '\0';
  return 0;
}

int
main() {
  char ciphertext_buffer[11];
  encrpypt(ciphertext_buffer, "THISISCOOL", "CRYPT");
  printf("%s\n", ciphertext_buffer);
  return 0;
}
#包括
#包括
int encrpypt(字符密文缓冲区[],字符明文[],字符密钥[]){
int i;

因为(i=0;iThanks:)我已经有一段时间没有用CNo编程了,朋友!我希望解释足够了。
#include <stdio.h>
#include <string.h>

int
encrpypt(char ciphertext_buffer[], char plaintext[], char key[], int size) {
  int i;
  for (i=0; i<strlen(plaintext); i++) {
    if (i > size - 1) break;
    ciphertext_buffer[i] = (char) ( ( ((int)plaintext[i] - 65 + (int)key[i%(strlen(key))] - 65) % 26 ) + 65 );
  }
  ciphertext_buffer[i] = 0;
  return 0;
}

int
main() {
  char ciphertext_buffer[11];
  encrpypt(ciphertext_buffer, "THISISCOOL", "CRYPT", sizeof(ciphertext_buffer));
  printf("%s\n", ciphertext_buffer);
  return 0;
}
#include <stdio.h>
#include <string.h>

int encrpypt(char ciphertext_buffer[], char plaintext[], char key[]) {
  int i;
  for (i=0; i<strlen(plaintext); i++) {
    ciphertext_buffer[i] = (char) ( ( ((int)plaintext[i] - 65 + (int)key[i%(strlen(key))] - 65) % 26 ) + 65 );
  }
 ciphertext_buffer[i] = '\0';
  return 0;
}

int
main() {
  char ciphertext_buffer[11];
  encrpypt(ciphertext_buffer, "THISISCOOL", "CRYPT");
  printf("%s\n", ciphertext_buffer);
  return 0;
}