只有字符数组的一部分被打印与函数

Only part of char array being printed with function

本文关键字:打印 函数 一部分 字符 数组      更新时间:2023-10-16

我尝试编写一个函数来打印字符数组,但由于某种原因,它只将函数的一部分打印到控制台。例如:

#include <iostream>
#include <stdio.h>
using namespace std;
void printString(char s[])
{
    int size = sizeof(s) - 1;
    for( int i = 0; i < size; i++)
    {
        cout << *(s + i);
    }
}
int main()
{
    char fruit[] = "Cherry";
    printString(fruit);
}

导致以下输出:

Che

无论我使用哪个单词,都只能打印 3 个字符。任何帮助将不胜感激。

无论我使用哪个单词,都只能打印 3 个字符。任何帮助将不胜感激。

int size = sizeof(s) - 1;不会做你认为它做的事情。

由于s在函数调用时衰减为指针,因此sizeof(s)总是为您提供指针的大小 - 1(在您的情况下似乎是 32 位指针 == 4 字节)。

请改用size_t size = strlen(s);

void printString(char s[]) {
    size_t size = strlen(s);
    for( size_t i = 0; i < size; i++) {
        cout << *(s + i);
    }
}

您可以执行以下操作:

void printString(char *s)
{
    while(*s!='')
    {
        cout << *s;
        s++ ;
    }
}

或者,您可以将代码编辑为:

#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
void printString(char s[])
{
    int size = strlen(s);
    for( int i = 0; i < size; i++)
    {
        cout << *(s + i);
    }
}
int main()
{
    char fruit[] = "Cherry";
    printString(fruit);
}

您的问题在以下行中:

int size = sizeof(s) - 1;

由于您正在使用函数来打印字符数组,因此字符数组:

char fruit[] = "Cherry";

衰减为指针,因此sizeof (s)等效于 sizeof (char*) ,在您的配置中为 4 个字节,因此 size 的值等于 3。

要解决此问题,您需要将数组的大小传递给函数,如下所示。

#include <iostream>
#include <stdio.h>
using namespace std;
void printString(char s[], int size) // Change here
{
    for( int i = 0; i < size; i++)
    {
        cout << *(s + i);
    }
}
int main()
{
    char fruit[] = "Cherry";
    printString(fruit, sizeof(fruit) / sizeof (fruit[0]) - 1); // Change here
}

即便如此,您也需要使用 sizeof(fruit) / sizeof (fruit[0]) 这样的结构来返回数组的真实大小,因为sizeof返回以字节为单位的变量大小,因此虽然它可以与char一起使用(因为char的大小是一个字节,但它可能不适用于其他类型的数组(例如 int数组)。

更新:如果是char数组,您需要将尝试打印的大小减小 1,因为字符串文字(或一般的类似 C 的字符串 - char 数组)以 NULL 字符结尾(char值等于 0),这是已知字符串结尾的机制。您实际上不需要打印它。