试图使用自己的strcpy并复制数组元素不工作?

时间:2013-03-01 03:52:51

标签: c

亲爱的朋友,             我是新来的,请查看我的代码。我的目的是将名称复制到结构数组元素中。我是c的新手,无法理解发生了什么......请指导我?

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

typedef struct new_st{

      const char name[100];
      int value;

    }var1;

char *myStringcopy(char *dst, const char *src)
{
         char *ptr;
         ptr  = dst;
        while(*dst++!=NULL)
        {
           *dst++=*src++;
          }

        return(ptr);
 }

 int main()
{

   char my_str[] = {"HelloWord", "MY var1", "my var2"};

   var1 *new_st1;


   new_st1 = malloc(sizeof(struct new_st));


     //trying just first name then i thought of using for loop for rest


      myStringcopy(my_str, new_st1->name[0]);

       printf("%s\n",new_st1->name[0]);



   return 0;


}

2 个答案:

答案 0 :(得分:1)

在此函数char *myStringcopy(char *dst, const char *src)中,您的第一个参数是destination。但是你用源地址作为第一个参数来调用这个函数。

在while while(*dst++!=NULL)

中,在while *dst++=*src++;循环NULL中递增目标地址两次int函数

您的条件是检查内容等于char *my_str[] = {"HelloWord", "MY var1", "my var2"};

字符串数组decalration应该与此{{1}}

类似

答案 1 :(得分:1)

坦率地说,您的代码似乎有很多逻辑错误。这是我的修复:

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

typedef struct new_st{
    char name[100]; //It should not be const because the content inside the array is intended to be modified.
    int value;
}var1;

char *myStringcopy(char *dst, const char *src) 
{
        char *ptr;
        ptr  = dst;
        while(*src!='\0') //src should be copy until a '\0' in src is reach.
           *dst++=*src++;
        *dst='\0'; //making dst a null-terminated string

        return(ptr);
 }

int main()
{

    const char* my_str[] = {"HelloWord", "MY var1", "my var2"}; //I have no idea why your code in this line even compile. The type of my_str should be char**, or an array of char* . Also, you should use const if the string will not be modified.
    var1 *new_st1;

    new_st1 = malloc(sizeof(struct new_st));
    myStringcopy(new_st1->name, my_str[0]); //new_st1->name[0] is a char. There is no reason to copy a char. Instead, you should copy a char* . I *guess* that you want to copy stuffs from my_str[n] to new_st1->name
    printf("%s\n",new_st1->name); //%s accepts a string(i.e. char*) , while new_st1->name[0] is a char. In this case, new_st1->name should be passed as a parameter, instead of new_st1->name[0]
    free(new_st1); //you should free() it after allocating memory with malloc() to avoid memory leak.
    return 0;
}

这是你想要的吗?

编辑:现在有解释。