#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Posts
    1
    Rep Power
    0

    Input through pointers


    I have a program getting input through pointers... It doesn't work in terminal in linux(gcc), but it works when coded in code blocks and in tc...

    The problem is that it works fine if there is clrscr statement, cant understand what the logic is, have checked in two pc's... Here is the code...

    #include<stdio.h>
    void main()
    {
    char *p;
    p="hello";
    clrscr();
    scanf("%s",p);
    printf("%s",p);
    }

    If there is no clrscr it shows null pointer assignment...
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,387
    Rep Power
    1871
    On what basis did you think
    scanf("%s","hello");
    was a good idea?

    > It doesn't work in terminal in linux(gcc), but it works when coded in code blocks and in tc...
    Ever since about 1990 (when ISO-C was first standardised), "strings" were defined as being constants, and so could be placed in read-only memory. Being read-only memory, modifications to them were not allowed at the OS level (you get a segfault). Modern compilers on modern operating systems place strings in read-only memory.

    GCC (the default compiler which comes with code blocks) used to have a transition flag called -fwritable-strings which would place "strings" in a writeable location (to aid transition of really old programs).
    But since release 4 of GCC, this is no longer an option.
    http://gcc.gnu.org/gcc-4.0/changes.html

    The fact that something works with TC (on DOS) doesn't mean squat. You can write all sorts of rubbish and get away with it on an OS which has no memory protection at all. Toy programs could abuse pointers no end, and it's only when programs got a bit larger that all the crap coding started to produce errors.

    Oh, and when posting code, please use [code][/code] tags, so it looks like this when you post.
    Code:
    #include <stdio.h>
    int main ( ) {  // yes, int, really!
      char buff[100];
      fgets( buff, sizeof(buff), stdin );
      printf("%s", buff );
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo