【发布时间】:2012-10-02 17:12:58
【问题描述】:
所以基本上 strcpy 将第二个参数的地址分配给第一个参数,但是它如何将数组作为第一个参数呢?就像在我的程序中一样,我尝试更改数组的地址,但不幸的是它不会编译。所以我不得不求助于制作一个字符指针变量来分配大写的返回值。我有什么误解吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char string[20];
char *Capitalize(char *str)
{
int i;
char *temp;
temp = malloc(sizeof(char)*(int)(strlen(str)+1));
for(i = 0;i < strlen(str);i++)
{
if(*(str+i) >= 'a' && *(str+i)<= 'z')
*(temp+i) = *(str+i) - 32;
else
*(temp+i) = *(str+i);
}
*(temp+i) = '\0';
return temp;
}
int main(void)
{
string word;
printf("Enter word to capitalize: ");
scanf("%19s",word);
word = Capitalize(word);
printf("%s",word);
return 0;
}
【问题讨论】:
-
"strcpy 将第二个参数的地址分配给第一个"不,它没有,它复制内容。
-
当您的示例代码都没有使用 strcpy() 时,为什么还要询问它?
-
@Glenn word = Capitalize(word) 这给出了一个错误,所以我想知道 strcpy() 如何将第二个参数的地址分配给数组,而显然它不能。我正在练习弦乐,所以我突然想到了这个想法。
-
附带说明,
sizeof(char)被定义为 1 并且强制转换没有用,因此您可以将malloc(sizeof(char)*(int)(strlen(str)+1));更改为malloc(strlen(str) + 1); -
您将
char *分配给char [20],这就是问题所在
标签: c arrays string pointers strcpy