亲爱的 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/