所以基本上 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()
进行复制,正如其名称所暗示的那样。将字符串复制到数组中是完全合法的。
当您对数组进行初始化时,例如:
char myarr[] = "hello";
您实际上是将字符复制到数组中。
您似乎将数组与指针混淆了( see here for some reason you can't treat them the same )
关于c - 当无法更改数组的地址时,strcpy() 如何将字符串复制到数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12695021/