Thread: problem understanding a pointer to an array of characters

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    347

    problem understanding a pointer to an array of characters

    Hi,

    i am trying to learn how to declare a pointer to an array of characters. And here is the code i have written. But iam getting a warning saying assignment from incompatible pointer type p = s.

    Code:
    #include <stdio.h>
    
    
    int main(int argc, char *argv[])
    {
    
    
    char (*p)[10]; // pointer to an array of 10chars
    char s[10] = "Hello";
    
    
    p = s;
    printf("%s",p);
    return 0;
    }
    can someone please explain me my mistake?
    Last edited by Satya; 12-17-2013 at 11:28 AM. Reason: mistake in the code

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    s is not a pointer to an array of chars; it is a pointer to a single char (the first in the array). &s is a pointer to an array of chars. (They have the same value, because s points to the first member of the array, but they have different types.)

  3. #3
    Registered User
    Join Date
    Feb 2012
    Posts
    347
    i never knew about this, i was always thinking s and &s are the same. thank you very much.

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by tabstop View Post
    s is not a pointer to an array of chars; it is a pointer to a single char (the first in the array).
    s is not a pointer at all. It is an array of 10 chars. When the name of an array is used in a context where a pointer is expected, however, then the name of an array is converted to a pointer (with value equal to the address of the first element, and type of "pointer to element of array").
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 10
    Last Post: 11-04-2012, 01:13 AM
  2. Replies: 13
    Last Post: 09-24-2008, 06:16 PM
  3. Replies: 7
    Last Post: 05-11-2008, 10:57 AM
  4. Array of pointer to characters
    By Stack Overflow in forum C Programming
    Replies: 3
    Last Post: 03-28-2005, 05:37 PM
  5. problem with making characters in an array different colors
    By o0obruceleeo0o in forum C++ Programming
    Replies: 0
    Last Post: 04-27-2003, 12:13 PM