尝试仅使用c在结构中复制c字符串
我试图只使用C将硬编码字符串插入到结构中的字符数组值中,所以我使用了memcpy,在另一篇文章中遵循了这个示例。但由于某些原因,我一直将看起来像地址的内容作为输出,我不知道为什么 我的控制台每次都会打印:[(27532592)(17524424)]和其他类似的长数字。我已经检查了很多关于如何将字符序列复制到c字符串的示例,看起来这一个是完全相同的。我可能只是理解指针有点困难。我不知道它为什么会吐出地址值。有人能指出我做错了什么吗?我为自己的无知道歉。我的缩写代码如下:尝试仅使用c在结构中复制c字符串,c,pointers,struct,memcpy,C,Pointers,Struct,Memcpy,我试图只使用C将硬编码字符串插入到结构中的字符数组值中,所以我使用了memcpy,在另一篇文章中遵循了这个示例。但由于某些原因,我一直将看起来像地址的内容作为输出,我不知道为什么 我的控制台每次都会打印:[(27532592)(17524424)]和其他类似的长数字。我已经检查了很多关于如何将字符序列复制到c字符串的示例,看起来这一个是完全相同的。我可能只是理解指针有点困难。我不知道它为什么会吐出地址值。有人能指出我做错了什么吗?我为自己的无知道歉。我的缩写代码如下: struct node
struct node
{
int key;
char month[20];
struct node *next;
};
struct node *head = NULL;
struct node *current = NULL;
//display the list
void printList()
{
struct node *ptr = head;
printf("\n[ ");
//start from the beginning
while(ptr != NULL)
{
printf("(%d,%d) ",ptr->key,ptr->month);
ptr = ptr->next;
}
printf(" ]");
}
//insert link at the first location
void insertFirst(int key, char * month)
{
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
memcpy(link->month, month, 20);
link->month[19] = 0; // ensure termination
//point it to old first node
link->next = head;
//point first to new first node
head = link;
}
int main() {
insertFirst(1,"Jan");
insertFirst(2,"March");
printf("Original List: ");
//print list
printList();
}
试一试
而不是“奇怪的输出”问题 试试看
而不是“奇怪的输出”问题 您正在打印指针
ptr->month
,而不是实际字符串。Try:
printf((%d,%s)”,ptr->key,ptr->month)代码>(%s
而不是%d
)。您打印的是指针ptr->month
,而不是实际字符串。
Try:printf((%d,%s)”,ptr->key,ptr->month)代码>(%s
而不是%d
)。注意链接->月[19]=0
是确保空字符终止的一个好主意。考虑避免魔术数字的替代方案。代码>memcpy(链接->月,月,链接大小->月);链接->月份【链接大小->月份-1】=0代码>或链接->月[0]=0;strncat(链接->月,月,链接大小->月)代码>备注链接->月[19]=0
是确保空字符终止的一个好主意。考虑避免魔术数字的替代方案。代码>memcpy(链接->月,月,链接大小->月);链接->月份【链接大小->月份-1】=0代码>或链接->月[0]=0;strncat(链接->月,月,链接大小->月)代码>给了你第一个以来最好的答案给了你第一个以来最好的答案
printf("(%d,%s) ",ptr->key,ptr->month);