Home > Back-end >  I am writing a program to say hello to a person after prompting the user for their name but it doesn
I am writing a program to say hello to a person after prompting the user for their name but it doesn

Time:01-09

I tried defining a string data type and a function to take user input inside a header file. The code takes the input correctly (I assume) but doesn't give the expected output.

This is the code for the header file named 'rosis.h'

#include <stdio.h>

typedef char *string;

string get_string(string s)
{
    string input;
    printf("%s", s);
    scanf("%s", input);

    return input;
}

This is the code for the main program named 'hello.c'

#include <stdio.h>
#include "rosis.h"

int main(void)
{
    string name = get_string("What is your name ?\n");
    printf("Oh hey %s!! It's nice to meet you!\n", name);
}

And this is the output

hello/ $ gcc hello.c -o hello
hello/ $ ./hello
What is your name ?
rosis
Oh hey (null)!! It's nice to meet you!

Note: I tried initializing the variable 'input' to an empty string in the header file, but then it just led to segmentation fault.

CodePudding user response:

segmentation fault because you variable is in read only segment.

CodePudding user response:

No memory is allocated for your string, so it will point to unallocated memory. When you try to read or write this memory you get undefined behavior which can be anything from an error, a null like you're getting, or the expected result.

Memory for a string must be allocated. Since we want this memory to live on after this function returns, we must use malloc.

#include <stdlib.h>

string get_string(string s)
{
    string input = malloc(256);
    printf("%s", s);

    // And restrict how much you read to avoid overflowing memory.
    scanf("%5s", input);

    return input;
}

This is not an efficient way to write a prompt function, but it will work.

A note about typedef char *string: C strings are not like strings you may be familiar with from other languages; don't try to pretend otherwise. It's very important to remember you are working with a pointer.

CodePudding user response:

Uninitialized value

scanf("%s", input); fails as the pointer input has not been assigned a value - a place in memory for scanf() to store input.

scanf("%s", ... fails to read a name with spaces

If your name is "Anime K", scanf("%s", input will only, at best, read "Anime" into input, leaving the " K\n" in stdin for the next input function.

Instead read a line of user input with fgets().

char input[100];
if (fgets(input, sizeof input, stdin)) {
  // Lop off a potential ending '\n'.
  input[strcspn(input, "\n")] = '\0';
  printf("Name :%s:\n", input);
}
  • Related