黑马程序员技术交流社区
标题:
请问这个程序有什么问题吗?
[打印本页]
作者:
千年的泪
时间:
2014-5-28 23:29
标题:
请问这个程序有什么问题吗?
本帖最后由 千年的泪 于 2014-5-29 10:45 编辑
这是我写的一个把输入的小写字符串转换成大写字符串的程序,请问有什么问题吗?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define SIZE 30
int main(void)
{
char str1[SIZE];
char *str2;
printf("请输入字符串:");
scanf("%s", str1);
printf("您输入的字符串是:");
printf("%s\n", str1);
int i = 0;
while (str1[i] != '\0')
{
str1[i] = toupper(str1[i]);
i++;
}
strcpy(str2, str1);
int j = 0;
while (str2[j])
{
printf("%c", str2[j]);
j++;
}
printf("\n");
return 0;
}
复制代码
作者:
xiaodixing
时间:
2014-5-28 23:55
这样改就没错了
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define SIZE 30
int main(void)
{
char str1[SIZE];
char str2[SIZE];//此处用定义一个字符串数组
printf("请输入字符串:");
scanf("%s", str1);
printf("您输入的字符串是:");
printf("%s\n", str1);
int i = 0;
while (str1[i] != '\0')
{
str1[i] = toupper(str1[i]);
i++;
}
strcpy(str2, str1);
int j = 0;
while (str2[j])
{
printf("%c", str2[j]);
j++;
}
printf("\n");
return 0;
}
作者:
XCodeRush
时间:
2014-5-29 00:22
回答:指针str2没有初始化,如果执行strcpy()函数
str1中的字符串会被复制到一个随机的内存区域,这是不可以的。
声明一个字符数组将会为字符串分配存储空间,但是声明一个指向字符的指针只会为该指针分配存储空间。
按照你的意思程序修改为:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define SIZE 30
int main(void)
{
char str1[SIZE];
char *str2;
char str3[SIZE]; // 分配一段名为str3的存储空间,等一下让指针str2指向它。
str2 = str3; // 将str3字符数组首元素的地址赋值给字符指针str2。
printf("请输入字符串:");
scanf("%s", str1);
printf("您输入的字符串是:");
printf("%s\n", str1);
strcpy(str2, str1);
while (*str2 = toupper(*str2)) {
putchar(*str2++);
}
putchar('\n');
return 0;
}
复制代码
作者:
千年的泪
时间:
2014-5-29 10:48
明白了{:3_64:}
作者:
天空角落
时间:
2014-5-29 11:08
学习中。。。{:2_41:}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2