【问题标题】:Struct with a struct field pointer带有结构字段指针的结构
【发布时间】:2015-12-21 12:38:31
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 20

typedef struct arr {
    char name[SIZE];
} arr;

typedef struct tz{
    struct arr *next;
} tz;


int main() {
    tz *tze;
    const char *value[SIZE];
    tze = (tz*) malloc(sizeof(tz)*5);
    int i;

    for(i = 0; i < 5; i++) {
        printf("insert value:\n");
        scanf("%s", value);
        strcpy(tze[i].next->name, value);
    }

    for(i = 0; i < 5; i++){
        printf("output:%s ",tze[i].next->name);
    }
    return 0;
}

嗨,上面有一个代码示例,这是我的问题。我想通过数组在“名称”字段中输入信息,其中每个单元格“链表”。不幸的是,来源不正确。有什么想法吗?

int main() {
    tz *tze;
    char *value;
    tze = (tz*) malloc(sizeof(tz)*5);
    value = (char*) malloc(sizeof(char)*SIZE);
    int i;



    for(i = 0; i < 5; i++) {
        printf("insert value:\n");
        fgets(value, SIZE, stdin);
        strncpy(tze[i].next->name, value,SIZE);
    }

    for(i = 0; i < 5; i++){
        printf("output:%s ",tze[i].next->name);
    }
    return 0;
}

我像这样更改了我的代码,但它仍然不起作用。我仍然收到信号错误错误。如果我使用:

strcpy(tze[i].next->name, value[i]);

我得到了一个错误指针,我相信 value[i] 我只指向第一个值单元格。 Insteal with value without [i] im 一般指向整个向量。

【问题讨论】:

标签: c struct linked-list


【解决方案1】:
const char *value[SIZE];

您已经声明了一个指向 char 的指针数组。但是您还没有为数组中的每个指针分配内存。

你在其中接受输入,所以你需要为数组中的每个指针分配内存。

现在看看这个循环 -

for(i=0;i<5;i++){  
   printf("insert value:\n");
   scanf("%s",value);          /*                <--problem  */
   strcpy(tze[i].next->name,value);       /*     same here   */
}

value 传递给 %s 将导致未定义的行为,因为 %s 需要 char * 并且您传递了一个指针数组。 strcpy 也有同样的问题。

所以正确的说法应该是-

scanf("%s",value[i]);                 // better use fgets 
strcpy(tze[i].next->name,value[i]);       

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-21
    • 2013-11-18
    • 2015-07-13
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    相关资源
    最近更新 更多