0

亲爱的朋友,我是新来的,请检查我的代码。我的意图是将名称复制到结构数组元素中。我是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;


}
4

2 回答 2

1

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

while(*dst++!=NULL)在 while 条件和 while 正文中的循环中将目标地址增加了两次 int 函数*dst++=*src++;

您的 while 条件检查内容等于NULL

字符串数组声明应该是这样的 char *my_str[] = {"HelloWord", "MY var1", "my var2"};

于 2013-03-01T04:13:31.800 回答
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;
}

这是你想要的吗?

编辑:现在解释一下。

于 2013-03-01T04:14:47.277 回答