Search code examples
cstringstructure

How can I add a value (string) in the structure field?


I have a problem with enterning a value (string) into structure field.. Can someone show me how it should look correctly? I wanna add a string (surname/nazwisko) from console's window into student1.nazwisko but i dont know how it should look. This is related to dynamic memory allocation

Code image

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>

struct dane {
    char* imie;
    char nazwisko[30];
    int nr_albumu;
};
struct node {
    struct node* next;
    struct node* prev;
    char nazwa[50];
};

int main(int argc, char* argv[])
{
    struct dane student1, student2, student3;
    student1.imie = "Arek";
    student1.nr_albumu = 374829;
    printf("Podaj nazwisko\n");
    //*(student1.nazwisko) = (struct dane*)malloc(20 * sizeof(*student1.nazwisko));
    
    //scanf_s("%s", student1.nazwisko);
    

    printf("Dane studenta 1: %s\t%s\t%d\n", student1.imie, student1.nazwisko, student1.nr_albumu);

    return 0;
}

Solution

  • The member nazwisko is an array statically allocated in the structure.

    To read a string to that via scanf(), you should specify the maximum number of characters to read to (at most) the buffer size minus one (this "minus one" is for the terminating null-character) and check if reading succeeded using the return value.

    With these points, it will be like this, for example:

    if (scanf("%29s", student1.nazwisko) != 1) {
        fputs("failed to read student1.nazwisko\n", stderr);
        return 1;
    }
    

    Note that %s format specifier reads strings until it hits to a whitespace character. If you want to read a line (until the newline character), you should use "%29[^\n]%*c" instead of "%29s". %29[^\n] means "read at most 29 characters until it hits to a newline character" and %*c means "read one character and ignore it". %*c here is for ignoring the newline character so that it won't prevent further readings.