c - 当无法更改数组的地址时,strcpy() 如何将字符串复制到数组?

标签 c arrays string pointers strcpy

所以基本上 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/

相关文章:

javascript - 如何在 TextView 输入中插入数字/文本?

c++ - 如何迭代 std::string 以获得一组 Freetype FT_ULong?

string-ref 函数不能正常工作

Javascript 字符串转二维数组

C:如何屏蔽宏参数中的逗号?

C:在文件中查找重复的字符串值

CS50 Pset 2.我的crack.c代码编译并运行,但不打印任何内容

javascript - HTML 数据列表中的动态数组

python - 使用 numpy.mean 分组

c - 创建链表时无限循环