Pointers and Strings (Answer)
char fred; strcpy(fred, "Today"); if (fred == "Today") printf("Of course!\n"); else printf("Today is not Today on planet C.\n");
Today is not Today on planet C.
== between strings compares pointers,
not string contents. Since the two strings must be in different
locations, the test is false.
The correct way to perform this test is
to use the string comparison library function. You
#include <string.h> at the top of your program,
then code the test
if(strcmp(fred, "Today") == 0).
char fred1 = "barney", fred2 = "barney", *fred3 = "barney"; printf("%d %d %d %d %d %d\n", strlen(fred1), strlen(fred2), strlen(fred3), sizeof fred1, sizeof fred2, sizeof fred3);
On my PC I get
6 6 6 7 20 4.
The last number may vary on different systems, but the others should
be the same. The first three numbers represent the length of the string,
which is six characters however the
string is stored. The
7 represents the
space required to store the string, 6 characters plus one byte for
the terminator. The
20 is just the storage size of
fred2, as declared. Since
fred3 is a pointer,
4 represents the size of one pointer,
not the string itself.
This will vary from
system to system, but 4 is probably the most common.
High-end machines (such as the the Alpha) will show 8, and
really ancient PC's will show 2. It may even vary between
different compilers on the same hardware.
sizeof is one of the few things in C
which treats an array and a pointer differently.
char sue = "susan", *p; for(p = sue; *p++; ) printf("%s", p); printf("\n");
The test increments
p, so that on the first iteration,
p is past the first character, and the loop body prints
usan. Each successive iteration prints one less character,
n, and finally
the empty string. When
p points to the character
the test is true, and leaves
p pointing to the
terminator. This prints out the empty string on the last iteration.
Then the test evaluates to the terminator character, and the loop exits.
char bill = "william"; strcpy(bill + 3, "ey coyote"); printf("%s\n", bill);
bill + 3 yields a pointer to position 3 of
bill, which is the second
ey coyote in memory
starting at that
l. The initial
char *sharon = "sharon"; while(*++sharon) printf("%c", sharon[-1]); printf("\n");
The test advances the pointer
sharon before checking
what character it points to, thus seeing, in successive tests,
n, and the terminator. On the terminator,
the loop exits. The body is executed with pointer
pointing to each of these, but prints the character in front of
sharon points using
sharon[-1]. Hence, the body prints
o. It does not print
it precedes the string terminator, and the test fails and terminates
the loop before the body can print
|Pointers and Arrays||Question||Dynamic Allocation in C|