[英]trying to copy a c string in a struct using only C
I'm trying to insert a hard coded string into a char array value in a struct using only C, so I used memcpy, following the example in another post. 我试图将硬编码的字符串插入仅使用C的结构的char数组值中,所以在另一篇文章中的示例之后,我使用了memcpy。 But for some reason, I keep getting what looks like an address as output, I'm not sure why. 但是由于某种原因,我一直在输出看起来像地址的东西,我不确定为什么。
my console prints out: [ (2,7532592) (1,7524424) ] and other long numbers like that every time. 我的控制台会打印出:[(2,7532592)(1,7524424)]以及其他类似的长数字。 I've checked so many examples on how to copy a sequence of characters into ac string, and it seems like this one was exactly the same. 我已经检查了许多示例,说明如何将一系列字符复制到ac字符串中,看来这是完全一样的。 I might just be having trouble understanding pointers. 我可能在理解指针方面遇到麻烦。 Im not sure why it's spitting out the address value. 我不确定为什么会吐出地址值。 Can anyone point out what I'm doing wrong? 谁能指出我做错了什么? I apologize for any lack of knowledge on my part. 对于我所缺乏的知识,我深表歉意。 My shortened down code is below: 我缩短的代码如下:
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();
}
You are printing the pointer ptr->month
, not the actual string. 您正在打印指针ptr->month
,而不是实际的字符串。
Try: printf("(%d,%s) ",ptr->key,ptr->month);
试试: printf("(%d,%s) ",ptr->key,ptr->month);
( %s
instead of %d
). (用%s
代替%d
)。
Try 尝试
printf("(%d,%s) ",ptr->key,ptr->month);
instead for the "curious output" problem. 而不是“好奇的输出”问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.