PDA

View Full Version : [C] question regarding char** assignments


serious
June 4th, 2009, 09:15
Hi all.

Code says more than thousand words ;)


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:


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
June 4th, 2009, 09:33
p = &s;

If I remember correctly the & without cast is returning void type, like using cast using malloc.

vivek
June 4th, 2009, 10:04
char s[64];
char *p;
p = s;
Another example
char s[64]="FreeBSD rockz!";
char *p;
p = s;
printf("%s\n",p);


See: http://oreilly.com/catalog/pcp3/chapter/ch13.html

serious
June 4th, 2009, 11:07
Viveks link enlightened me. Thanks for the read.


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
June 4th, 2009, 22:25
This is a real titty twister, why does this work?



int main(){

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

serious
June 5th, 2009, 09:04
For more information on this issue see:

http://www.lysator.liu.se/c/c-faq/c-2.html

2.4 answers your question, Business_Woman.

serious
June 5th, 2009, 11:01
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.

yavuzg
June 6th, 2009, 00:24
char s[64];
char **p;
p = &s;
return (0);
}



Please read "& operator applied to arrays does nothing." section of the below link:

http://www.fredosaurus.com/notes-cpp/arrayptr/arraysaspointers2.html

And one more:
http://publications.gbdirect.co.uk/c_book/chapter5/arrays_and_address_of.html

I think this links will help...