Very simple questions about pointers
Author |
Message |
David C #1 / 33
|
 Very simple questions about pointers
Somebody, please tell me why this is okay main() { char *p = "one two three"; Quote: }
but the following is not! main() { char *p; printf("enter a string"); gets(p); Quote: }
If the second example is bad because the pointer is not pointing to a valid piece of memory, why is the first one okay. I know that the way to correct the first one is to add char str[80]; p = str; Also please read the following and tell me if I'm right *p++ /*first increments and then accesses the value at the new address*/ *p+1 /*fist access the value and then increments*/ *p(p+1) /*same as *p++ */ Thank you in advance, David "pointers are driving me insane" Cho
|
Tue, 11 Nov 1997 03:00:00 GMT |
|
 |
Jeffrey Tayl #2 / 33
|
 Very simple questions about pointers
: Somebody, please tell me why this is okay : main() : { : char *p = "one two three"; : } This allocates space to hold the string in quotes and space for the pointer, and sets the pointer to the address of the quoted string. : but the following is not! : main() : { : char *p; : printf("enter a string"); : gets(p); : } : If the second example is bad because the pointer is not pointing to a : valid piece of memory, why is the first one okay. I know that the way to : correct the first one is to add : char str[80]; : p = str; This is a way to correct the second. : Also please read the following and tell me if I'm right : *p++ /*first increments and then : accesses the value at the new address*/ This accesses, then increments (post-increment, the increment operator is after the pointer). *++p first increments, then accesses (pre-increment). : *p+1 /*fist access the value and then increments*/ This accesses the value and adds one to the value, not the pointer. : *p(p+1) /*same as *p++ */ No way to parse this occurs to me. This is not valid C, unless p is a pointer to a function. -- ===================================== Jeff T "Blues with a feeling... =====================================
|
Tue, 11 Nov 1997 03:00:00 GMT |
|
 |
Michael Shiel #3 / 33
|
 Very simple questions about pointers
Quote:
> Somebody, please tell me why this is okay > main() > { > char *p = "one two three"; > }
When you say `"one two three"', you get a const char * to that string, somewhere in memory. That pointer is then used to initialize p. This is similar to when you say `printf("one two three")', and get a const char * to that string, somewhere in memory. That pointer is then passed to printf(). Quote: > but the following is not! > main() > { > char *p; > printf("enter a string"); > gets(p); > }
p is never initialized, and thus points to an undefined location. You then write to it with gets(). This is Bad. Quote: > I know that the way to > correct the first one is to add > char str[80]; > p = str;
Except that you might be reading a string longer than 79 characters (plus the terminating nul), and that p is unnecessary. char buf[80]; fgets(buf, sizeof(buf), stdin); Quote: > Also please read the following and tell me if I'm right > *p++ /*first increments and then > accesses the value at the new address*/
No, `*p++' first accesses, then increments. The behavior you described is `*++p'. Quote: > *p+1 /*fist access the value and then increments*/
NB: Unary operators bind more tightly than binary operators, so this is `(*p) + 1', not what you want. (Another reason to put spaces around binary operators!) Even if you meant `*(p + 1)' (same as, and more commonly written as, `p[1]'), no, p is not changed. Instead, it creates a new temporary anonymous pointer with value p + 1, and dereferences it. Quote: > *p(p+1) /*same as *p++ */
No, this would call a function named p(), which hopefully returns a nonnull pointer, because you're dereferencing the result. I'm not sure what you were trying to do. Quote: > Thank you in advance, > David "pointers are driving me insane" Cho
The best thing to do is to get a copy of K&R2, and study chapter 5 until you understand all of it. -- Shields.
|
Tue, 11 Nov 1997 03:00:00 GMT |
|
 |
Ray Park #4 / 33
|
 Very simple questions about pointers
: Somebody, please tell me why this is okay : main() : { : char *p = "one two three"; : } In this example, the compiler sets aside memory on the stack for the 'literal' string "one two three", and assigns the pointer 'p' to the string's address. : but the following is not! : main() : { : char *p; : printf("enter a string"); : gets(p); : } ..and you have it right, p is not pointing anywhere helpful... : If the second example is bad because the pointer is not pointing to a : valid piece of memory, why is the first one okay. I know that the way to : correct the first one is to add : char str[80]; : p = str; Ray Parker 'A mind is a terrible thing to waste? No, a mind is not a terrible thing, nor one to be wasted! I suggest that we try to use our minds though, as otherwise they will be wasted, and that would be a terrible thing!'
|
Tue, 11 Nov 1997 03:00:00 GMT |
|
 |
Stig Hemm #5 / 33
|
 Very simple questions about pointers
Quote:
> Why is > main() { char *p = "one two three"; } > OK?, but the following is not! > main() { char *p; printf("enter a string"); gets(p); }
Whenever the compiler sees a "string" it allocates enough memory for the content. (Well, almost whenever...) So, 'char *p = "one two three";' means something like 'allocate 14 bytes of memory, put the string "one two three\0" there and store a pointer to this area in p.' Clear? More or less the same thing also happens in you second example with 'printf("enter a string");' which means something like 'Allocate 15 bytes of memory, store "enter a string\0" there and pass a pointer to that area to printf(). In the second program the pointer p never gets a value. When you call gets(p) it writes to memory wherever p might be pointing, which usually have bad effects. The main point to remember is that for a pointer to do something useful, it must point to _allocated_ memory. "doublequotes" allocates memory. Variable declarations, including arrays[] allocate memory. And malloc() allocates memory. In my book, one of C's strengths is that it never allocates memory behind the scenes. Programmers always have to ask nicely for memory, which means that they can have perfect knowledge of all memory used by the program (yeah right :) Quote: > char str[80]; p = str;
In you second example simply 'char p[80];' will do the job. Quote: > *p++ /*first increments and then > accesses the value at the new address*/
No, Since the ++ is _after_ the p, the value of p is incremented _after_ it is used. Quote: > *p+1 /*fist access the value and then increments*/
Sort of, but not in the way you are probably thinking. If we look at your first example, what happens is that p is accessed, giving 'o'. The we add 1 to that giving 'p'. (Assuming ASCII) The pointer is never changed. Quote: > *p(p+1) /*same as *p++ */
No.You are calling p as a function, which simply doesn't make sense in this case. Quote: > David "pointers are driving me insane" Cho
Well, C-style pointers certainly takes some getting used to, but in the end they will seem to work in a perfectly natural way. Of course, this might be taken as a sign of insanity. Happy hacking!
pvv - ProgramVareVerkstedet ("The Software Workshop", a student society) .unit - UNiversitetet I Trondheim .no - NOrway, a minor kingdom in northern Europe. PS: There are lots of nits to pick in this article. Please don't.
|
Tue, 11 Nov 1997 03:00:00 GMT |
|
 |
Jeffrey Tayl #6 / 33
|
 Very simple questions about pointers
: Somebody, please tell me why this is okay : main() : { : char *p = "one two three"; : } This allocates space to hold the string in quotes and space for the pointer, and sets the pointer to the address of the quoted string. : but the following is not! : main() : { : char *p; : printf("enter a string"); : gets(p); : } : If the second example is bad because the pointer is not pointing to a : valid piece of memory, why is the first one okay. I know that the way to : correct the first one is to add : char str[80]; : p = str; This is a way to correct the second. : Also please read the following and tell me if I'm right : *p++ /*first increments and then : accesses the value at the new address*/ This accesses, then increments (post-increment, the increment operator is after the pointer). *++p first increments, then accesses (pre-increment). : *p+1 /*fist access the value and then increments*/ This accesses the value and adds one to the value, not the pointer. : *p(p+1) /*same as *p++ */ No way to parse this occurs to me. This is not valid C, unless p is a pointer to a function. -- ===================================== Jeff T "Blues with a feeling... =====================================
|
Tue, 11 Nov 1997 03:00:00 GMT |
|
 |
Tim O'Malle #7 / 33
|
 Very simple questions about pointers
hola.
Quote: > Somebody, please tell me why this is okay > main() > { > char *p = "one two three"; > } > but the following is not! > main() > { > char *p; > printf("enter a string"); > gets(p); > } > If the second example is bad because the pointer is not pointing to a > valid piece of memory, why is the first one okay. I know that the way to > correct the first one is to add
When reading the main() function, the compiler allocates static space for the string "one two three". (If you would like to see which strings have static space, run the command 'strings' on the executable. 'strings' is a UNIX command.) Once the compiler has space allocated for the string, it assigns the address of that space to the variable "p". Thus, "p" is now initialized with the address of the string "one two three". In the second case, "p" never gets initialized. Because it is never initialized, it does not point to valid space. Quote: > Also please read the following and tell me if I'm right > *p++ /*first increments and then > accesses the value at the new address*/ > *p+1 /*fist access the value and then increments*/ > *p(p+1) /*same as *p++ */
The "real" answer is to use parenthesis to ensure that your code a) works as you expect it and b) is understandable to someone else So, you should be writing: *(p++) /* increment and then dereference */ (*p)++ /* dereference and then increment */ etc. -- .................................................................. . . Complex problems have . . happy daze . simple, . . -tim O . easy-to-understand, . . . wrong answers. . ..................................................................
|
Tue, 11 Nov 1997 03:00:00 GMT |
|
 |
Tanmoy Bhattachar #8 / 33
|
 Very simple questions about pointers
Quote: Shields) writes:
<snip> |> When you say `"one two three"', you get a const char * to that string, |> somewhere in memory. That pointer is then used to initialize p. Not in C. In C, string literals have type char[] (i.e. it is an array that _decays_ to a pointer: it is not a pointer; and its type is char not const char.) Modifying them (or trying to :-) is not a constraint violation, and hence the compiler is not required to diagnose this; but it does lead to undefined behaviour. Cheers Tanmoy --
Tanmoy Bhattacharya O:T-8(MS B285)LANL,NM87544-0285,USA H:#3,802,9 St,NM87545 Others see <gopher://yaleinfo.yale.edu:7700/00/Internet-People/internet-mail>, <http://alpha.acast.nova.edu/cgi-bin/inmgq.pl>or<ftp://csd4.csd.uwm.edu/pub/ internetwork-mail-guide>. -- <http://nqcd.lanl.gov/people/tanmoy/tanmoy.html> fax: 1 (505) 665 3003 voice: 1 (505) 665 4733 [ Home: 1 (505) 662 5596 ]
|
Wed, 12 Nov 1997 03:00:00 GMT |
|
 |
Ajoy Krishnan #9 / 33
|
 Very simple questions about pointers
:: Somebody, please tell me why this is okay :: main() :: { :: char *p = "one two three"; :: } :In this example, the compiler sets aside memory on the stack for the 'literal' :string "one two three", Unlikely. A string literal has static storage duration; ie., it exists throughout the lifetime of the program. A compiler is not very likely to use the stack as the memory storage for a string literal. :and assigns the pointer 'p' to the string's address. Shouldn't that be: "assigns the string's address to the pointer 'p'"?
Quote: >When you say `"one two three"', you get a const char * to that string, >somewhere in memory.
You actually get a char * to that string, somewhere in memory. This is because string literals are defined to have array of char type, which decays to pointer-to-char. Though intuitively it makes more sense to consider them array of const char, preserving existing code seems to have been given higher priority. ------ /* "Hell is other people" - Jean Paul Sartre */ /* Ajoy Krishnan T, Senior Software Engineer, Hughes Software Systems, New Delhi - 19, India.
|
Wed, 12 Nov 1997 03:00:00 GMT |
|
 |
Seth LaFor #10 / 33
|
 Very simple questions about pointers
Quote:
>: *p(p+1) /*same as *p++ */ >No way to parse this occurs to me. This is not valid C, unless p is a >pointer to a function.
In which case, p+1 is invalid, since you can't do arithmetic to a function pointer. This could be valid, though, if p were a preprocessor macro: #define p x- which causes the above to be expanded to: *x-(x-+1) which is parsed as: (*x) - (x - (+1)) I somehow doubt that this is what was originally intended though. :) Seth
|
Wed, 12 Nov 1997 03:00:00 GMT |
|
 |
Ajoy Krishnan #11 / 33
|
 Very simple questions about pointers
Quote:
>> Why is >> main() { char *p = "one two three"; } >> OK?, but the following is not! >> main() { char *p; printf("enter a string"); gets(p); } >.Whenever the compiler sees a "string" it allocates enough memory for >the content. (Well, almost whenever...)
Yeah, the "almost" escape is well-taken. A compiler is not required to allocate memory for a string literal; if a string literal with the same spelling already exists, it is free to reuse it. Thus, with: char *p = "one two three"; char *q = "one two three"; there is no guarantee that p != q (there is no guarantee that p == q either). Quote: >The main point to remember is that for a pointer to do something >useful, it must point to _allocated_ memory. "doublequotes" allocates >memory.
Not necessarily. See the previous example. Quote: >Variable declarations, including arrays[] allocate memory.
Most variable *definitions* allocate memory. Some variables, like union members, do not really allocate memory, they reuse existing memory. Quote: >> char str[80]; p = str; >In you second example simply 'char p[80];' will do the job.
Not if you want to use: Quote: >> *p++ /*first increments and then >> accesses the value at the new address*/ >PS: There are lots of nits to pick in this article. Please don't.
Hey, this is comp.lang.c.moderated :-) [exactly. Most of the useful information is imparted through nitpicking here. -mod] ----- /* "I make a living picking nits." */ /* Ajoy Krishnan T, Senior Software Engineer, Hughes Software Systems, New Delhi - 19, India.
|
Wed, 12 Nov 1997 03:00:00 GMT |
|
 |
Dan P #12 / 33
|
 Very simple questions about pointers
Quote:
>: *p(p+1) /*same as *p++ */ >No way to parse this occurs to me. This is not valid C, unless p is a >pointer to a function.
This is not valid C, period. If p is pointer to function, p+1 is meaningless (what is the size of a function? :-) Dan -- Dan Pop CERN, CN Division
Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
|
Thu, 13 Nov 1997 03:00:00 GMT |
|
 |
Karl Heu #13 / 33
|
 Very simple questions about pointers
Quote:
>So, you should be writing: > *(p++) /* increment and then dereference */
I disagree. "*p++" is an *extremely* common idiom, and it behooves any serious C programmer to understand it without the redundant parens. It takes a little *longer* for me to mentally parse "*(p++)", because it's less common; and I also have to wonder whether the author meant to write something else. (This is not to say that *all* redundant parens should be avoided; something like "w << x + y & z" is probably harder to understand than its fully-parenthesized counterpart. It's a judgement call.)
|
Thu, 13 Nov 1997 03:00:00 GMT |
|
 |
Ajoy Krishnan #14 / 33
|
 Very simple questions about pointers
Quote:
>>: *p(p+1) /*same as *p++ */ >>No way to parse this occurs to me. This is not valid C, unless p is a >>pointer to a function. >[...] >This could be valid, though, if p were a preprocessor macro: >#define p x- >which causes the above to be expanded to: > *x-(x-+1) >which is parsed as: > (*x) - (x - (+1))
And then? How is this lisp-ish code interpreted? If x is a pointer (which it has to be, for the *x to make sense) the x - +1 subexpression generates a pointer. The *x on the left generates the pointed to type. The subtraction violates a constraint. (ptr-to-T subtracted from type T always violates ISO 6.3.6; T subtracted from ptr-to-T could be valid if T were an integral type). Note that, in C, -(a - b) and b - a are not necessarily interchangeable. #define p(arg) #arg makes the code valid, just for argument's sake. Of course, the usefulness of the expression *"p+1" is open to further debate. ------ /* "Thinking down to the level of a compiler gives me a headache." */ /* Ajoy Krishnan T, Senior Software Engineer, Hughes Software Systems, New Delhi - 19, India.
|
Thu, 13 Nov 1997 03:00:00 GMT |
|
 |
Daniel Rei #15 / 33
|
 Very simple questions about pointers
Quote:
>>: *p(p+1) /*same as *p++ */ >>No way to parse this occurs to me. This is not valid C, unless p is a >>pointer to a function. >This is not valid C, period. If p is pointer to function, p+1 is >meaningless (what is the size of a function? :-)
What if 'p' is an array of pointers to functions, each taking as its argument a pointer to a similar function? I think there's some way of doing this, but it makes my head hurt. At any rate, it is clearly not the same as '*p++'. -- Dan Reish R&D Programmer, Systems Operator Packard Business Systems, Ann Arbor, MI, USA
|
Fri, 14 Nov 1997 03:00:00 GMT |
|
|
Page 1 of 3
|
[ 33 post ] |
|
Go to page:
[1]
[2] [3] |
|