Why is this simple program not working?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • karan173
    New Member
    • Dec 2011
    • 3

    Why is this simple program not working?

    Code:
    #include<stdio.h>
    
    int main()
    {
        char *s="hello";
        *(s+2)='a';
        printf("%s",s);
    	return 0;
    }
    it gives a runtime error, however if i declare s as a character array like s[]="hello", it works, why?
  • manontheedge
    New Member
    • Oct 2006
    • 175

    #2
    the problem is in the line

    Code:
    char *s="hello";
    when you create a dynamic array, as you have done with

    Code:
    char* s
    you need to reserve space in memory for it. You do that like this ...

    Code:
    char* s = new char[sizeof("hello")];
    then, you can't assign a string of characters ("hello") to a dynamic char array using the equals sign. You have to copy the characters like this

    Code:
    strcpy(s, "hello");
    ... should work aside from that

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Also,

      Code:
      char *s="hello";
      says s is the address of the h, which is const. It's const becuse "hello" is a const array since it is a literal.

      When you try to change this literal at run time you crash trying to change a const value.

      You may do as manontheedge recommends rvided you delete the array.

      If you need a local variable cod it this way:

      Code:
      char s[] ="hello";
      Now this says that s is a char array allocated on the stack and initialized to hello+\0. The array has 6 elements.

      Comment

      Working...