#include<stdio.h> main () { char *p="abcd"; while(*p!='\0') { printf("%s",*p); p++; }
时间: 2024-03-15 10:44:31 浏览: 18
这段代码有一个错误,因为在printf函数中使用了%s格式化字符,但是传入的是一个字符类型(char),应该使用%c格式化字符。正确的代码应该是这样的:
```c
#include <stdio.h>
int main() {
char *p = "abcd";
while (*p != '\0') {
printf("%c", *p);
p++;
}
return 0;
}
```
这段代码的功能是输出字符串"abcd"中的每一个字符。
相关问题
#include<stdio.h> char *pstract (char*,char*); int main(void) { char s1[10]={'a','b','c','d'}; char s2[2]={'e','f'}; char *w; w = pstract(s1,s2); printf("%s",w); return 0; } char *pstract(char *s1,char *s2) { int n; char *p = s1; char *q = s2; n = sizeof(s1)/sizeof(char); p += n-1; while(*q != '\0') { *p = *q; p++; q++; } *++q='\0'; return s1; }
这段代码的功能是将字符串 s2 追加到字符串 s1 的末尾,并返回 s1 的首地址。但是有几个问题需要注意:
1. s1 的长度应该至少为 7,因为 s2 的长度为 2,加上 s1 的最后一个元素需要留给字符串结束符 '\0',所以至少要预留 3 个位置。
2. 在函数中计算 s1 的长度应该使用 strlen 函数来获取字符串的实际长度,而不是使用 sizeof 函数获取数组的大小。
3. 在追加完 s2 后,需要手动在 s1 的末尾添加结束符 '\0',而不是在 s2 的末尾添加。
4. 在返回 s1 的首地址时,应该返回指针变量 p,而不是 s1。因为 p 已经指向了 s1 的末尾。
修改后的代码如下:
```
#include <stdio.h>
#include <string.h>
char *pstract(char*, char*);
int main(void) {
char s1[10] = "abcd";
char s2[2] = "ef";
char *w = pstract(s1, s2);
printf("%s", w);
return 0;
}
char *pstract(char *s1, char *s2) {
int n = strlen(s1);
char *p = s1 + n;
char *q = s2;
while (*q != '\0') {
*p++ = *q++;
}
*p = '\0';
return s1;
}
```
#include <stdio.h> fun (char *s, int n1, int n2) char c: while (n1<n2) c= sinll:sinll=sIn2l:sIn2]=c: n1++; n2-- D、 main) char all="ABCD": fun (a, 0,3) ; printf("gs\n",a):
这段代码有语法错误,应该是:
```
#include <stdio.h>
void fun(char *s, int n1, int n2) {
char c;
while (n1 < n2) {
c = s[n1];
s[n1] = s[n2];
s[n2] = c;
n1++;
n2--;
}
}
int main() {
char a[] = "ABCD";
fun(a, 0, 3);
printf("%s\n", a);
return 0;
}
```
这段代码的作用是将字符串 "ABCD" 中下标在 n1 至 n2 之间的字符反转。在 main 函数中,我们首先将字符串 "ABCD" 存储在字符数组 a 中,然后调用函数 fun,将其反转。最后,我们打印反转后的字符串 "DCBA"。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)