-3
#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;
}

Hi, above there is a code sample that is my problem. I would like to enter information in a field 'name' through an array, where each cell 'linked list. Unfortunately, the source is not correct. Some idea?

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;
}

I changed my code like this but it still doesnt work. Im still getting a sigment fault error. If i use :

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

I got a error pointer and i trust that with value[i] im pointing only to the firts cell of value. Insteal with value without [i] im pointing generally to the whole vector.

Jilz
  • 31
  • 5

1 Answers1

1
const char *value[SIZE];

You have declared an array of pointer to char . But you haven't allocated memory to each pointer in array.

You take input in it , so you need to allocate memory to each of pointer in array .

Now see this loop -

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

Passing value to %s will cause undefined behaviour as %s expects a char * and you pass an array of pointer . And same problem is in strcpy .

So correct statement would be -

scanf("%s",value[i]);                 // better use fgets 
strcpy(tze[i].next->name,value[i]);       
ameyCU
  • 16,489
  • 2
  • 26
  • 41