指向C字符串的指针

Pointer to a C-String?

本文关键字:指针 字符串 指向      更新时间:2023-10-16

关于CS赋值的介绍,我正在Visual Studio 2010中编写一个C++程序,该程序返回一个整数,并接受一个指向C字符串的指针作为参数。我知道我需要在int main之外创建一个函数才能成功,但如果可能的话,我不太确定如何初始化指向预定义char数组的char指针数组。

这个程序的目的是在预定义的限制内从用户那里获得评论,然后通知所述用户该评论有多少个字符(包括空白)

错误是:不能将"char"类型的值分配给"char*"类型的实体;

这是我的程序,不编译:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
//function protoype
void evalStr(char arr[]);
//variable
int length;

//main function
int main()
{
const int SIZE = 201;
char arr[SIZE];
char *str[SIZE];
cout << "Please enter a comment under " << (SIZE - 1) << " characters to calculate it's length: ";
*str = arr[SIZE];
cin.getline(arr, SIZE);

length = strlen(*str);
evalStr(arr);
system("PAUSE");
return 0;
}
//function defintion
/*  get the string
count the number of characters in the string
return that number
*/
void evalStr(char arr[])
{
printf("The length of the entered comment is %d charactersn", length);
}

如果有一种通用的方法来使用char指针数组或字符串指针,那么可以重新编写此代码以返回字符串的值,而不是使用printf语句。我到底做错了什么?

编辑:这是这个程序的更新版本,它编译、运行并在达到或超过字符限制时通知用户。

// Accept a pointer to a C-string as an argument 
// Utilize the length of C-string in a function. 
// Return the value of the length
// Display that value in a cout statement.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;

//variables
const int SIZE = 201;
int length;
char arr[SIZE];
char *str;

//main function
int main()
{
str = &arr[0];
// Size - 1 to leave room for the NULL character
cout << "Please enter a comment under " << (SIZE - 1) << " characters to calculate it's length: ";

cin.getline(arr, SIZE);

length = strlen(str);
if (length == (SIZE - 1))
{
cout << "Your statement has reached or exceeded the maximum value of " 
<< length << " characters long.n";
}
else
{
cout << "Your statement is ";
cout << length << " characters long.n";
}

system("PAUSE");
return 0;
}
//function defintion
/*  get the string
count the number of characters in the string
return that number
*/
int countChars(int)
{
length = strlen(str);
return length;
}

让我们谈谈main中正在发生的事情:

int main()
{

好的,你会得到201个字符的字符串。看起来很合理。

const int SIZE = 201;

您已经声明了一个201个字符的数组:

char arr[SIZE];

现在,您声明了一个由201个指针组成的数组,这些指针指向字符。我不知道你为什么要那样做。我怀疑你认为这做了一些与实际不同的事情:

char *str[SIZE];

这是合理的(除了"它的"意味着"它是",但你想要占有的版本,"它"):

cout << "Please enter a comment under " << (SIZE - 1) << " characters to calculate it's length: ";

这会将第201个字符分配给字符指针数组中的第一个字符指针。这是一个错误,因为:

  • 数组是零索引的,因此第201个字符(当您开始以零计数时)超出了数组的末尾
  • 您还没有将arr中的内存初始化为任何内容
  • 您正在将char分配给char *

因此,鉴于上述情况,我不确定您为什么要这样做:

*str = arr[SIZE];

这看起来很合理:

cin.getline(arr, SIZE);

这是一个错误,因为str此时没有指向包含有效字符串的内存。

length = strlen(*str);

当您"指向字符串"时,实际上您指向了字符串的第一个字符。字符串的末尾可以通过查看连续的内存位置找到,直到找到一个包含空字节的位置。所以你的代码应该是:

char *str;         // can point at a character
// ....
str = &arr[0];    // point to the first character of arr
// ....
length = strlen(str);