Thread: question about array and pointer

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    41

    Post question about array and pointer

    Code:
    char* sche  = "Sep 29, 19:34";
    Code:
    char  sche[]  = "Sep 29, 19:34";
    I would like to ask that 2 lines of codes above are the same meaning in C.What is the meaning of the first code and the second code
    Thanks

  2. #2
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    The first is a pointer to a string literal while the second is a 14 element array of char.
    In the first case the contents of the string literal cannot be altered; in the second case the contents of sche[] can be modified.

  3. #3
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    And in the first occassion you can assign pointer "sche" to something else, while in the second you cannot assign "sche" to something else

  4. #4
    Registered User
    Join Date
    Mar 2008
    Posts
    41
    If I declare
    Code:
    char* sche  = "Sep 29, 19:34";
    Then I can extract each char from "sche" by iterating through "sche.However if I try to use strtok() on schelike following
    Code:
    char delim[] = "-";
    char* token1;
    token1 = strtok(input,delim);
    printf("token1%s\n",token1);
    The compiler complains
    Code:
    red 322 % new.out
    Segmentation fault
    red 323 %
    I need some help to understand this problem. Can someone give me an answer for this.
    Thanks

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    char *s = "thisisastringliteralandyoucannotmodifywhatishereinquotes";
    char a[] = "thisisanarrayofunspecifieddimensionsandyoucanmodifyitscontentsprovidedyoudonotoverrunthelengthallocatedbythisassignment";
    Does that explain it better?


    Quzah.
    Hope is the first step on the road to disappointment.

  6. #6
    Registered User rpbear's Avatar
    Join Date
    Nov 2009
    Posts
    18
    the first one used as a initial expression of string,not just a pointer,which means it can't be use if not give it the space with malloc or somewhat else when you using it not as a initial expression.
    the 2th shows sche is a array,it can be as large as you give to it after the = operator

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting the matrix question..
    By transgalactic2 in forum C Programming
    Replies: 47
    Last Post: 12-22-2008, 03:17 PM
  2. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  3. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM