1、下列程序的运行结果是:【 】#include <string.h>char *ss(char *s){ return s+strlen(s)/2; }main( ){ char *p, *str = ”abcdefgh”; p=ss(str); printf(“%s\n”, p);}
时间: 2024-03-31 09:32:19 浏览: 31
该程序的运行结果是 "efgh"。函数 `ss` 中,`strlen(s)` 返回字符串 `s` 的长度,`strlen(s)/2` 则返回字符串 `s` 的中间位置(向下取整),`s+strlen(s)/2` 则返回从字符串 `s` 中间位置开始的子字符串。在 `main` 函数中,`str` 是字符串 "abcdefgh" 的首地址,`p` 被赋值为 `ss(str)` 的返回值,即从 "abcdefgh" 中间位置 "e" 开始的子字符串 "efgh" 的首地址,最后在屏幕上输出该子字符串。
相关问题
下方代码的功能是获取输入的字符串的长度,请指出代码哪里存在问题:#include<stdio.h> #include<stdlib.h> #include<string.h> int getLen(char* ss) { int* p = ss; int c = 0; while (*p != '\0') { printf("%c\n",*p); p++; c++; } return c; } int main() { char ss[30] = {0}; gets(ss); int len=getLen(ss); printf("len=%d",len); return 0; }
这段代码中存在以下问题:
1. 在第5行中,将字符指针p直接赋值为字符串指针ss是错误的,因为字符指针和字符串指针是不同的类型。正确的方式是将字符指针p指向字符串指针ss所指向的字符串的第一个字符,即 `int* p = &ss[0];` 或 `char* p = ss;`。
2. 在第12行中,使用了不安全的函数`gets`,该函数会导致缓冲区溢出漏洞,应该使用更安全的函数`fgets`替代。
3. 在第13行中,输出的字符串长度不包括字符串末尾的'\0',因此应该在返回值前减去1。
修改后的代码如下:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getLen(char* ss) {
char* p = ss;
int c = 0;
while (*p != '\0') {
printf("%c\n", *p);
p++;
c++;
}
return c - 1;
}
int main() {
char ss[30] = {0};
fgets(ss, 30, stdin);
int len = getLen(ss);
printf("len=%d", len);
return 0;
}
```
4.当执行以下程序时,如果输入 ABC, 写出程序输出的结果 ( )。 #include <stdio.h> #include <string.h> void main() {char <tex>ss[10]='1,2,3,4,5''</tex> gets(ss); strcat(ss,"6789"); printf("%s\n",ss);}
这段程序是有语法错误的,因为在声明字符数组 `ss` 时,使用了错误的语法:
```c++
char ss[10]='1,2,3,4,5'
```
应该使用双引号来表示字符串,而不是单引号。正确的写法是:
```c++
char ss[10] = "1,2,3,4,5";
```
同时,在 `main` 函数中应该加上返回类型 `int`。修正后的程序如下:
```c++
#include <stdio.h>
#include <string.h>
int main() {
char ss[10] = "1,2,3,4,5";
gets(ss);
strcat(ss, "6789");
printf("%s\n", ss);
return 0;
}
```
假设输入的是 "ABC",则程序输出的结果是:
```
ABC6789
```
首先使用 `gets` 函数读入字符串,然后使用 `strcat` 函数将字符串 "6789" 拼接到 `ss` 中,最后输出拼接后的字符串 "ABC6789"。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)