difference between char *prt and char prt

This is a discussion on difference between char *prt and char prt within the C Programming forums, part of the General Programming Boards category; Hi All is there a difference between Code: char *prt = "hello" and Code: char prt[] = "hello" I noticed ...

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    72

    difference between char *prt and char prt

    Hi All

    is there a difference between

    Code:
    char *prt = "hello"
    and

    Code:
    char prt[] = "hello"
    I noticed because I got a 'Bus error' when I do

    Code:
    #include <string.h>
    #include <stdlib.h>
    #include <stdio.h>
    
    main(){
      char *prt = "abc=def" ;
      char *out = strtok(prt, "=") ;
    }
    but it works when I use ptr[]!

    thnx
    LuCa

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    The first one (char *ptr) is a "const" string literal, which means it cannot (or should not) be changed.

    The second one (char ptr[]) is a character array, initialized with a value, but the value *can* be changed.

    The reason you get an error using strtok() on a const is because strtok() actually destroys the string you are processing in the process. You will see what happens if you add a printf() after strtok() to show the string. Other functions, like sscanf, strcmp, and strstr do not alter the string analysed, so it is not a problem. strtok() is fine with "normal" strings, ie, character arrays.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    72
    ok, thnx a lot!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting Linked Lists
    By DKING89 in forum C Programming
    Replies: 6
    Last Post: 04-09-2008, 08:36 AM
  2. Conversion Char To Char * Problem
    By ltanusaputra in forum Windows Programming
    Replies: 3
    Last Post: 03-01-2008, 02:06 PM
  3. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 12:58 PM
  4. comparing fields in a text file
    By darfader in forum C Programming
    Replies: 9
    Last Post: 08-22-2003, 09:21 AM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 05:10 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21