`

Below Code not working :-

#include<stdio.h>
void main()
{
    char *s;
    gets(s);
    printf("%c",s);

}

Dani AI

Generated

The root cause is that char *s; only declares a pointer — it does not allocate storage for characters. Writing input into that uninitialised pointer invokes undefined behavior. pointed this out (you need a real array or allocated memory), and is right to warn that undefined behavior can appear to “work” sometimes and then break.

Safe options (choose one):

  • Declare a buffer with a known size on the stack. Always account for the terminating '\0'.
  • Allocate with malloc (remember to free) and check the result; allocate length+1 for the terminator.
  • Point to a string literal if you only need a read-only string (do not write into it).

Also: printf("%c", s) is wrong because %c expects a char, not a char *. To print the first character use s[0] or *s (after checking the string is non-empty). gets is unsafe and has been removed from the C standard — use fgets (or controlled scanf formats) instead; see the C reference for details: fgets and gets (removed).

Example pattern to read safely, strip newline, print the string and its first character:

#include <stdio.h>
#include <string.h>

int main(void) {
    char buf[128];
    if (fgets(buf, sizeof buf, stdin)) {
        size_t len = strlen(buf);
        if (len && buf[len-1] == '\n') buf[len-1] = '\0';
        printf("%s\n", buf);
        if (buf[0] != '\0') printf("%c\n", buf[0]);
    }
    return 0;
}

Troubleshooting tips: compile with -Wall -Wextra -std=c11, use AddressSanitizer (-fsanitize=address) or Valgrind to catch out-of-bounds/invalid frees, and inspect warnings. was right about using int main(void) rather than void main().

Recommended Answers

All 5 Replies

Does it compile? Does it run to completion? Does it crash? Where? What was the input? What was the expected output? What actually happened? Details, details, details.

This one's pretty easy though. Let's take a look at gets.

char * gets ( char * str );

Further down on the page, we get to a description of str.

str
Pointer to an array of chars where the C string is stored.

Key word is "array". You don't have an array of chars, you have a pointer that doesn't point to anything so there's no place to store what the user enters. Try changing str to an array of chars in your program. We'll make it size 100 because it's a nice round number. So change line 4 to this...

char s[100];

As for line 6, you don't want to give a "%c" arguiment a char* parameter. Give it a char paramter. Or better yet, since you read in a string, make it a "%s".

printf("%s", s);

Note that you're in trouble if the user types 100 or more characters in. The buffer will be overrun. Read this and consider fgets instead.

http://www.gidnetwork.com/b-56.html

Hi,
Do you want to say that, if i define pointer to a char,it doesn't reserve the memory for entering a string?? However, my problem being, the below code does take the string,prints it in the 6th line, but doesn't print the character at the adress. And Yes, now i also have memory issues,since we are not exactly telling in the code, the places to be reserved.

#include<stdio.h>
        void main()
        {
        char *s;
        gets(s);
        printf("%s",s);
        printf("%c",s);
        }

Do you want to say that, if i define pointer to a char,it doesn't reserve the memory for entering a string??

Exactly.

However, my problem being, the below code does take the string,prints it in the 6th line, but doesn't print the character at the adress.

Your problem is that invoking undefined behavior (eg. writing to memory you don't own) can do anything, including work as expected. That's why the whole "it works for me" argument is invalid when it comes to undefined behavior. Unfortunately, working as expected gives people a false sense of security in broken code, which is why you have to know what causes undefined behavior and avoid it.

It's int main(void)

commented: Correct. But if you're going to correct someone, explain why. It helps them learn. +14
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HOW_MANY_CHARS 2
int main()
{
   char *s = NULL;//does not point to allocated memmory

   s = (char*) malloc (sizeof(char) * HOW_MANY_CHARS);//create nice old string
   memset(s, 0, HOW_MANY_CHARS);//initialize it to zeroes

   gets(s);//though better to use getchar and check for overflow

   printf("[%s]\n",s);// print whole c string
   printf("[%c]\n",s[0]);//acces first char and print it

   free(s);

   return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.