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

    Join Date
    Feb 2011
    Posts
    13
    Rep Power
    0

    Question about static string


    I know I can not change its value after initialization and can;t change its address using realloc

    But I am not sure as for when it becomes static when it is declared in struct. lets say I have the following struct:

    Code:
    struct staticstring 
    { 
        char* str;
    }typedef static_t;
    And the next function:

    Code:
    getStaticString(static_t* str_struct)
    {
       scanf("%s",str_struct->str);
    }
    that does not work.

    BUT this does work:

    Code:
    getStaticString(static_t* str_struct)
    {
       str_struct->str="abc";
       printf("string is %s \n",str_struct->str);
    }

    so my question is when it actually initialize and decides whether it is static or not?
    because I could use malloc or calloc there and then realloc freely because it would become dynamic....

    I am guessing it is done in the compilation mode so if I initialize it with a string "aaa" it knows to store it in the static storage and when I use malloc it dynamically allocates it so it naturally gains restriction or permission for writing by the user.

    am I write on this?

    It means user can not enter a static string?
    (even as initiation).
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Location
    India
    Posts
    95
    Rep Power
    4
    char * str defined in structure is not pointing to any valid location that's why you are not able to use scanf on it,there is no concept of static string on it.

    you cant modify static string because it's part of code section and user are not allowed to modify because its read only.

    and when you use malloc or calloc it will allocate memory and in heap section and you will lost your previous string.

IMN logo majestic logo threadwatch logo seochat tools logo