c - 尝试使用自己的 strcpy 并复制数组元素不起作用?

标签 c

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


}

最佳答案

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

您在 while 条件和 while 主体中的循环 while(*dst++!=NULL) 中将目标地址递增两次 int 函数 *dst++=*src++;

您的 while 条件正在检查内容是否等于 NULL

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

关于c - 尝试使用自己的 strcpy 并复制数组元素不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15150210/

相关文章:

C编程: A Simple Countdown Program

C程序求2个矩形面积的并集

c++ - Quicksort 出现段错误

c - 嵌入式C代码无法解释的语法错误;预期……在 '{' token 之前

c++ - C/C++ 编译器如何在头文件中找到原型(prototype)的定义?

c - 如何让我的程序使用 BSD 打印其 github 版本号?

c++ - 通过 WinSocket 客户端/服务器应用程序重用套接字

c# - 从 c# 调用 c zlib 解压缩

c - 使用 RSA_PKCS1_OAEP_PADDING 进行 RSA 签名

c++ - 使用另一个可变参数函数的未命名参数调用可变参数函数