用指针的传递该怎么写,不用string.h
时间: 2024-03-23 15:35:52 浏览: 9
如果你想用指针传递字符串,可以使用字符数组作为参数。以下是一个示例函数:
```c++
void printString(char* str) {
int i = 0;
while (str[i] != '\0') {
cout << str[i];
i++;
}
}
```
在上面的函数中,我们将一个字符指针作为参数,然后使用循环遍历该字符串并打印每个字符。请注意,在这种情况下,我们没有使用任何 string.h 函数。
相关问题
编写评定成绩等级的函数 函数名:类似wlbgrade(wlb三个字母必须替换成您姓名的汉语拼音缩写) 形参:仅一个整型指针类型的形参,用于传递实参中成绩(分数)在内存中的地址 返回值:字符串指针类型,用于返回评定的成绩等级字符串(优秀、良好、中等、及格、不及格)在内存中的地址 功能:根据形参所指向的成绩(分数)用多分支if或switch语句判断其等级,等级以字符串的形式保存在字符数组内。提示:要使用string.h及strcpy函数,返回等级字符串的地址
好的,以下是您要求的函数代码:
```c
#include <string.h>
char* wlbgrade(int* score) {
char* grade = (char*)malloc(sizeof(char) * 10);
if (*score >= 90) {
strcpy(grade, "优秀");
}
else if (*score >= 80) {
strcpy(grade, "良好");
}
else if (*score >= 70) {
strcpy(grade, "中等");
}
else if (*score >= 60) {
strcpy(grade, "及格");
}
else {
strcpy(grade, "不及格");
}
return grade;
}
```
这个函数的作用是根据传入的成绩(分数)评定其等级,并将等级字符串的地址返回。使用了`string.h`库中的`strcpy`函数将等级字符串复制到动态分配的内存空间中,以免出现指针错误。
用c语言实现用指针传递参数,实现两个字符串的互换
可以使用指针传递参数来实现两个字符串的互换。以下是一个用C语言实现的示例代码:
```c
#include <stdio.h>
#include <string.h>
void swap(char **str1, char **str2) {
char *temp = *str1;
*str1 = *str2;
*str2 = temp;
}
int main() {
char str1[] = "Hello";
char str2[] = "World";
printf("Before swap:\n");
printf("str1: %s\n", str1);
printf("str2: %s\n", str2);
swap(&str1, &str2);
printf("After swap:\n");
printf("str1: %s\n", str1);
printf("str2: %s\n", str2);
return 0;
}
```
在这个示例代码中,我们定义了一个名为 `swap` 的函数,它使用了指针传递参数来交换两个字符串。该函数使用了一个 `char **` 类型的指针,这是因为我们需要传递两个字符串的指针,而每个字符串本身也是一个指针。
在 `main` 函数中,我们声明了两个字符串 `str1` 和 `str2`,并将它们传递给 `swap` 函数。在 `swap` 函数中,我们使用了一个 `temp` 变量来保存 `str1` 的值,然后将 `str1` 的指针指向 `str2`,将 `str2` 的指针指向 `temp`,从而实现了两个字符串的互换。
最后,我们在 `main` 函数中输出交换后的字符串,以验证函数是否正确工作。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.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)