Thread: Why did the string become immutable in this function ?

  1. #1
    Registered User
    Join Date
    Jul 2010
    Posts
    3

    Why did the string become immutable in this function ?

    I compiled the following code on gcc :
    Code:
    # include <stdio.h>
    fun(char str[100])
    {
    	str[0]='c';
    }
    int main()
    {
    	fun("wah");
    	return 0;
    }
    On running it gave Segmentation fault. On running the debugger, I found that the problem was in :
    Code:
    str[0]='c';
    If I first take "wah" in a string variable, and then pass that variable to fun(), then there is no problem. Why is this happening ?

  2. #2
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    String literals are actually "const char *". They could be stored in areas of memory you are not allowed to modify (and it looks like the case here).

    "char str[100]" in parameter list is the same as "char *str". C passes arrays as pointers (to the first element).

  3. #3
    Registered User
    Join Date
    Jul 2010
    Posts
    3
    Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  2. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  3. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  4. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 02:28 PM
  5. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM

Tags for this Thread