【发布时间】:2014-11-11 03:45:13
【问题描述】:
我想要一些专业的建议来制作一个 char *x 字符串数组(具有不同大小的 const char 名称)有人会帮助分配一个列表以适应结构名称的大小(qSep->front->name ))
尝试 1:我的基本情况有效,所以我开始制作多个打印语句。第一个没有放入。我的 gdb 导致 printf("Found in List %s has name\n", x[0]);
代码和数据结构如下。
size_t separation( const User *user1, const User *user2 ) {
int len= 0;
char *x;
//use contains
queueSep *qSep =(struct queueSep*) malloc(sizeof(struct queueSep));
int count = 0;
//pre-condition: the user is not the same as user2
if ( user1->name == user2->name ) { //str compare
return 0;
}
qSep->front = convert(user1, NULL, count);
printf("Conversion complete for %s \n",qSep->front->name);
len++;
x = malloc(len*sizeof((const char*)qSep->front->name));
x[len-1] = qSep->front->name;
printf("Found in List %s has name\n", x[0]);
while( qSep->front != NULL) {
//check if front of the queue is the finish USER
if ( (const char*)qSep->front->name == user2->name ) {
return qSep->front->separationCount;
} else { //add all the neighbours on the queue with separation size incremented
struct node *currAmigo = qSep->front->sepAmigos->amigos_Queue->front;
if ( currAmigo == NULL ) {
//is that a bad thing?
}
while ( currAmigo != NULL ) {
for(int i = 0; i < len; ++i) {
printf("List amigo for %s has name %s\n", currAmigo->data->name, x[i]);
/*
//if(strcmp(x[i], currAmigo->data->name))
{
goto end_nested_loop;
}
*/
}
//make a qSep node
struct sepNode *node = convert(currAmigo->data, NULL, count+1);
len++;
x = realloc(x, len*sizeof(int));
x[len-1] = currAmigo->data->name;
//insert the sepNode into the end of the queue
que_insSepqueue(qSep, node);
//go to Next Amigo in top of Queue
currAmigo=currAmigo->next;
}
end_nested_loop:
count++;
//remove the node
que_deqSep( qSep );
}
}
return -1;
}
转换后的结构
typedef struct sepNode {
const char *name;
struct Friends_struct *sepAmigos;
size_t *separationCount;
struct sepNode *sepNodeNext;
}sepNode;
typedef struct queueSep{
struct sepNode *front; //front of queue
}queueSep;
//How to make a list
typedef struct User_struct {
const char *name;
Friends amigos;
} User;
EXTRA(将节点转换为表示分离长度)
sepNode *convert( const User *user1, const User *user2, int count) {
sepNode *sepNode1=
sepNode1 = (struct sepNode*) malloc(sizeof(struct sepNode));
sepNode1->name = user1->name;
sepNode1->sepAmigos = user1->amigos;
sepNode1->separationCount = count;
sepNode1->sepNodeNext = NULL;
return sepNode1;
}
【问题讨论】:
-
当gdb停在
printf("Found in List %s has name\n", x[0])这一行时,打印出x和x[0]的值。由于您将x声明为char *,因此x[0]是一个字符,与%s格式不兼容。 -
你想让
x指向什么?在一行中你有x = malloc(len*sizeof((const char*)qSep->front->name));,它指向一个char *的数组,但稍后你有x = realloc(x, len*sizeof(int));,这将使它指向一个ints 的数组。无论哪种情况,看起来char *x都不是您想要声明x的方式。 -
x[len-1] 被调用,但 x[0] 没有初始化。 @MarkPlotnick 在我修复代码后确实出现了这个错误,很好。我相信 %s 与 char 兼容,但这不是错误。谢谢你。投票或我关闭。
标签: c arrays gdb queue breadth-first-search