c语言,编写一个程序,用移动指针求字符数组的长度
时间: 2024-05-02 15:18:38 浏览: 19
以下是一个用移动指针求字符数组长度的 C 语言程序:
```c
#include <stdio.h>
int main() {
char str[] = "Hello, World!"; // 定义一个字符数组
char *ptr = str; // 定义一个指针,指向字符数组的首地址
int len = 0; // 初始化字符数组长度为 0
while (*ptr != '\0') { // 只要指针指向的字符不是字符串结束符 \0,就继续移动指针
ptr++; // 指针向右移动一个字符
len++; // 字符数组长度加一
}
printf("The length of the string is %d\n", len); // 输出字符数组长度
return 0;
}
```
在上面的程序中,我们首先定义了一个字符数组 `str`,并用字符串常量 "Hello, World!" 初始化它。然后,我们定义一个指针 `ptr`,并将它指向字符数组的首地址。接下来,我们用一个 while 循环来移动指针,每次移动一个字符,并将字符数组长度加一,直到指针指向字符串结束符 \0。最后,我们输出字符数组的长度。
运行上面的程序,输出如下:
```
The length of the string is 13
```
可以看到,我们成功地用移动指针的方法求出了字符数组的长度。
相关问题
用c语言:编写一个类似库函数strlen()的函数,求字符串的长度
可以使用指针来实现一个类似库函数`strlen()`的函数,下面是一个示例代码:
```c
#include <stdio.h>
int my_strlen(char *str) {
int len = 0;
while (*str != '\0') {
len++;
str++;
}
return len;
}
int main() {
char str[] = "hello world!";
int len = my_strlen(str);
printf("The length of the string is %d\n", len);
return 0;
}
```
在这个示例代码中,`my_strlen()`函数接收一个指向字符串的指针作为参数,然后在循环中通过判断当前指针所指的字符是否为字符串结束符`\0`来计算字符串的长度。注意,这里使用了指针的自增运算符`++`来移动指针指向下一个字符。
在`main()`函数中,我们定义了一个字符串数组`str`,并将其传递给`my_strlen()`函数来计算字符串的长度。最后,我们使用`printf()`函数将字符串的长度输出到控制台。
用c语言利用指针编写程序,统计字符串的长度。(不要使用求字符串长度函数) 输入格式: gets() 输出格式: "The length of the string is %d\n"
下面是一个利用指针计算字符串长度的C语言程序:
```c
#include <stdio.h>
int main() {
char str[100];
char *p = str;
int len = 0;
printf("Enter a string: ");
gets(str);
while (*p != '\0') {
len++;
p++;
}
printf("The length of the string is %d\n", len);
return 0;
}
```
程序首先定义了一个字符数组 `str` 和一个指向字符数组的指针 `p`,并将指针初始化为指向数组的第一个元素。然后使用 `gets()` 函数读取用户输入的字符串。
接下来,程序通过循环遍历字符数组,每遍历一个字符就将计数器 `len` 加一,并将指针向后移动一个位置,直到遍历到字符串的结尾字符 `\0`。
最后,程序输出字符串的长度。注意,输出格式需要使用 `%d` 占位符将计数器 `len` 的值插入到输出字符串中。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)