代码如下:
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
typedef int Element;
struct LIST;
typedef struct LIST *list;
struct LIST{
Element x;
list next;
};
#define alloc_list_p malloc(sizeof(struct LIST))
char *get_asterisk(int n)
{
char *asterisk = "*";
printf("in get_asterisk %d\n" , n*sizeof(char));
asterisk = malloc(n*sizeof(char));
while(n){
--n;
strcat(asterisk , "*");
}
return asterisk;
}
int main()
{
char *t;
t = get_asterisk(10);
printf("%s\n" , t);
free(t);
list the_first_of_list ,the_second_of_list , the_third_of_list;
the_first_of_list = alloc_list_p;
the_second_of_list = alloc_list_p;
the_third_of_list = alloc_list_p;
the_first_of_list->x = 2;
the_second_of_list->x= 3;
the_third_of_list->x=4;
the_first_of_list->next = the_second_of_list;
the_second_of_list->next = the_third_of_list;
the_third_of_list->next = NULL;
list p;
p = the_first_of_list;
while(p!=NULL)
{
printf("%d\n" , p->x);
p = p->next;
}
return 0;
}
如果第三十一行的10改成5那么这些星号就输出正常,10以上的都输出有些不正常,不知道这是为什么?有高手能解答不?
本文探讨了C语言中链表的创建及内存分配问题,通过具体代码示例展示了如何构建链表,并讨论了一个涉及字符串内存分配的案例。当尝试分配过长的字符串时出现了异常情况。

被折叠的 条评论
为什么被折叠?



