我如何在C中最初调用char指针?

我如何在C中最初调用char指针?,c,C,我想复制一个常量字符(cpattern),所以我尝试了 char *pattern; /* the destination that I want to copy the cpattern */ strcpy(pattern, cpattern); where cpattern is the char that I want to copy. 使用 void StrCopy(char *pcDest, const char *pcSrc) { char* temp = pcDest;

我想复制一个常量字符(cpattern),所以我尝试了

char *pattern; /* the destination that I want to copy the cpattern */
strcpy(pattern, cpattern);
where cpattern is the char that I want to copy.
使用

void StrCopy(char *pcDest, const char *pcSrc)
{
  char* temp = pcDest;
  while(*pcSrc!='\0') {
    *temp = *pcSrc;
    temp++;
    pcSrc++;
  }
  *temp = '\0'; 
}

但两者都会产生相同的错误:“pattern”在此函数中未初始化使用。

以下是代码中的问题:

char *pattern;            // pattern is not initialized
                          // it points nowhere

strcpy(pattern, pattern); // copying the source onto itself
                          // doesn't make much sense
你可能想要这个:

char source[] = "Hello World!";
char destination[100];

strcpy(destination, source);
printf("Destination: %s\n", destination);
// or StrCopy(destination, source)

StrCopy
功能在我看来还可以。

您可能还希望为
目的地使用动态分配的内存,因此

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

strcpy(模式,模式)它应该做什么?从某个未初始化的指针复制到自身。即使已初始化,也没有意义。请编辑您的问题。先读一读。其中有一些明显的错误,如Eugene Sh.在上面评论的内容。您的
StrCopy
函数可能会更好,但它是正确的。所以这个错误一定是因为它的用法。你得到答案了吗,还是还有什么问题?如果是这样,你必须编辑你的问题或写另一个问题。别担心,我们会帮你的。你在使用之前填好图案了吗?还是你刚刚申报的?请提供一些代码

//do not forget to allocate an extra room for the terminating 0 at the end 
char *destination = (char *) malloc(sizeof(char) * (strlen(source) + 1));
//check if allocation was successful.
if(destination){
    //now copy from source to destination
    strcpy(destination, source);//or StrCopy(destination, source);
}
.
.
.
//then after using it do not forget to free the allocated memory:
free(destination);
//you are good to go!