[C] question regarding char** assignments

serious

New Member


Messages: 5

Hi all.

Code says more than thousand words ;)

PHP:
int
main(int argc, char **argv)
{
        char            s[64];  /* s is of type (char *) here, right? */
        char          **p;

        /*
         * This assignment warns me about "assignment from incompatible
         * pointer type"
         */
        p = &s;

        /*
         * This works without warning. But as I'm not sure why I have to cast
         * here I would like to avoid it... Or to make sure this is legal and
         * not too bad style. So, what do you think about it?
         */
        p = (char **)&s;

        return (0);
}
This gives me:

Code:
gcc -Wall --ansi test.c
test.c: In function `main':
test.c:11: warning: assignment from incompatible pointer type
I would like to know why I get this warning and how I can avoid it "the right way".

Any help will be appreciated.
 

vermaden

Son of Beastie

Reaction score: 1,180
Messages: 2,764

Code:
p = &s;
If I remember correctly the & without cast is returning void type, like using cast using malloc.
 
OP
OP
serious

serious

New Member


Messages: 5

Viveks link enlightened me. Thanks for the read.

Code:
int
main(int argc, char **argv)
{
        char            s[64] = "test 123";     /* s is of type (char *)
                                                 * here, right? */
        char           *t;
        char          **p;

        /*
         * After thinking a little more about it, I guess this is the
         * cleanest way to achieve my goal. There is a subtle difference
         * between arrays and pointers. See Viveks link ;)
         */
        t = &s[0];              /* turn s into a (char *) */
        p = &t;                 /* use & to turn (char *) into (char **) */

        return (0);
}
 

Business_Woman

Active Member

Reaction score: 6
Messages: 152

This is a real titty twister, why does this work?

PHP:
int main(){

int s = 2["Howdy"];
printf("%d",s);
        return 0;
        }
 
OP
OP
serious

serious

New Member


Messages: 5

Please forget my previous post (I can't edit it yet). I re-read Business_Woman's post and figured out my answer has nothing to do with it :r

Anyway one last link: http://c-faq.com/aryptr/aryptr2.html This is the answer to my original question and the more recent version of the link I posted in the last post.
 
Top