我有一个功课,它是:
写下面的函数代码,这个函数应该计算s里面的字节数,直到它不是'\ 0'.
功能:
Run Code Online (Sandbox Code Playgroud)unsigned len(const char* s);
真的我不知道这个功课是什么意思,有人可以写这个功课的代码吗?还有更多人可以解释一下"Const char*s"是什么意思吗?如果你能用一些例子来解释那将是完美的.
这是我正在尝试做的代码:
unsigned len(const char* s)
{
int count=0;; int i=0;
while (*(s+i)!=0)
{
count++;
i++;
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
但是在主要功能中我不知道应该写什么,顺便说一句,我写的是:
const char k='m';
const char* s=&k;
cout << len(s) << endl;
Run Code Online (Sandbox Code Playgroud)
结果总是4!我真的不知道该怎么办这个问题,如果我只能在const char中存储一个字符,那么结果总是一样的.这个问题究竟在寻找什么?
作业意味着你应该编写一个行为如下的函数:
int main() {
char s[] = {'a','b','c','\0'};
unsigned s_length = len(s);
// s_length will be equal to 3 ('a','b','c', not counting '\0')
}
Run Code Online (Sandbox Code Playgroud)
我认为这里不太可能有人为你做功课.
据推测,如果要求您执行此操作,您的类已涵盖函数参数,指针和数组.所以我猜你在问const.const char* s表示s指向a const char,这意味着你不允许修改char.也就是说,以下是非法的:
unsigned len(const char *s) {
*s = 'a'; // error, modifying a const char.
}
Run Code Online (Sandbox Code Playgroud)
以下是有关编写函数指针的基本知识.首先,在这种情况下,指针指向数组中的元素.那是:
char A[] = {'a','b','c','\0'};
char const *s = &A[0]; // s = the address of A[0];
Run Code Online (Sandbox Code Playgroud)
指针指向或引用 a char.为此,char你取消引用指针:
char c = *s;
// c is now equal to A[0]
Run Code Online (Sandbox Code Playgroud)
因为s指向数组元素的点,所以可以添加和删除指针以访问数组的其他元素:
const char *t = s+1; // t points to the element after the one s points to.
char d = *t; // d equals A[1] (because s points to A[0])
Run Code Online (Sandbox Code Playgroud)
您还可以使用数组索引运算符:
char c = s[0]; // c == A[0]
c = s[1]; // c == A[1]
c = s[2]; // c == A[2]
Run Code Online (Sandbox Code Playgroud)
你会用什么顺序查看数组的每个元素,增加索引?
您提出的解决方案看起来应该可以正常工作.你得到4的结果的原因只是巧合.你可能会得到任何结果.你调用函数的方式有问题:
const char k='m';
const char* s=&k;
cout << len(s) << endl;
Run Code Online (Sandbox Code Playgroud)
是没有'\0'保证最后.您需要创建一个元素,其中一个元素为0:
const char k[] = { 1,2,3,0};
const char* s = &k[0];
cout << len(s) << '\n'; // prints 3
char m[] = { 'a', 'b', 'c', 'd', '\0', 'e', 'f'};
cout << len(m) << '\n'; // prints 4
char const *j = "Hello"; // automatically inserts a '\0' at the end
cout << len(j) << '\n'; // prints 5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1959 次 |
| 最近记录: |