Thread: char pointer problem

  1. #1
    Registered User
    Join Date
    May 2006

    char pointer problem


    Why will this lead to crash:

    char *tmp = "(some)(stupid)(string)\0";
    char *p = tmp;
    int length = strlen(tmp);
    if ( (p[0] == '(') && (p[length-1] == ')') ) {
    	p[length-1] = '\0';
    	printf("%s \n", p);
    I just want to remove parenthesis at the begging and end..

    Thanks for help

  2. #2
    uint64_t...think positive xuftugulus's Avatar
    Join Date
    Feb 2008
    char *tmp = "(some)(stupid)(string)\0";
    The compiler places that string on non-modifyable memory space, but it is legal to have a pointer to it. It is a constant string. If you need to modify it, acquire a copy first.
        goto johny_walker_red_label;
    johny_walker_blue_label: exit(-149$);
    johny_walker_red_label : exit( -22$);
    A typical example of programming practices.

  3. #3
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    If you want a copy, then make an array:

    char tmp[] = "(some)(stupid)(string)\0";
    That will make tmp an array that starts out with an implicit copy of the string from its read-only location.

    Also, string literals don't need to have the '\0' char appended at the end. If the array is big enough to hold the array, the '\0' will be there in the array. By not specifying the size, the array is made large enough to hold the entire array + the '\0'. So this is all you really need:

    char tmp[] = "(some)(stupid)(string)";

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help understanding info in a header file
    By hicpics in forum C Programming
    Replies: 8
    Last Post: 12-02-2005, 11:36 AM
  2. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 08:32 AM
  3. comparing fields in a text file
    By darfader in forum C Programming
    Replies: 9
    Last Post: 08-22-2003, 08:21 AM
  4. I'm having a problem with data files.
    By OmniMirror in forum C Programming
    Replies: 4
    Last Post: 05-14-2003, 09:40 PM
  5. Problem with Link List
    By Unregistered in forum C Programming
    Replies: 10
    Last Post: 04-24-2002, 11:49 PM
Website Security Test