473,397 Members | 2,077 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

String Problem?

Hi all,

I found
char x[4]={"my"};
can be compiled.

But
char x[4];
x={"my"};
can not be compiled.

Why?
Any suggestions will be appreciated!

Best regards,
Davy

Oct 7 '05 #1
28 2073
In article <11**********************@g44g2000cwa.googlegroups .com>,
Davy <zh*******@gmail.com> wrote:
I found
char x[4]={"my"};
can be compiled. But
char x[4];
x={"my"};
can not be compiled. Why?


Because that's how it is.

Initializers on a variable declaration have syntaxes available
that are not available in other places.
--
Camera manufacturers have temporarily delayed introduction of
sub-millibarn resolution bio-hyperdimensional plasmatic space polyimaging,
but indications are that is still just around the corner.
Oct 7 '05 #2
sat
Ok davy, to understand this,
you need some background on the way C / C++ deals with array names and array
pointers.

char* p1 = "hello";
char p2[] = hello;

now.. p1 and p2 can be used in most places interchangeable.. like
1. p1[0];
2. *(p2+2)
etc etc..
but there are few exceptioins for this.
1. p2++
2. p2 - =10;
3. p2 = p1
4. char* ch = "world" ;
p2 = ch;
ARE NOT VALID

the thumb rule is "you cant do any modication operations to the address
pointed by the array name". You will get an LValue required error.


"Davy" <zh*******@gmail.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
Hi all,

I found
char x[4]={"my"};
can be compiled.

But
char x[4];
x={"my"};
can not be compiled.

Why?
Any suggestions will be appreciated!

Best regards,
Davy

Oct 7 '05 #3

Davy wrote:
Hi all,

I found
char x[4]={"my"};
can be compiled.
Yes, but it is better to do this:

char x[] = "my";

This way just enough space for "my" is provided.
But
char x[4];
x={"my"};
can not be compiled.
Because the type of x in...

char x[4];

....is effectively...

char* const x;

....which means the value of the pointer "x" is constant - may not be
modified, whereas doing this...

x={"my"}; //- actually x = "my"...

....attemps to modify the pointer x, which is why you get a compiler
error.

Suggestions as follow:

char x[100] = { '\0' };
std::ostrstream os( x, sizeof(x) );
os << "Hooh, hah" << std::ends; //don't forget std::ends;

or...

std::string x("my");

or...

char x[4] = { '\0' };
strcpy( x, "my" );

Remember, the contents of the array which exists at the address
location whereto x points, is modifiable. The address itself (or the
value of the ptr) is not.

Regards,

W


Why?
Any suggestions will be appreciated!

Best regards,
Davy


Oct 7 '05 #4
"Davy" <zh*******@gmail.com> wrote in news:1128661915.425811.133260
@g44g2000cwa.googlegroups.com:

Hi all,

I found
char x[4]={"my"};
can be compiled.

But
char x[4];
x={"my"};
can not be compiled.

Why?


Remember. sweetums, 'x' is a pointer when you declare it that way. If that
assignment actually worked, it would be changing the pointer itself, not
the data that the pointer points to.

Be glad it didn't compile, because the resulting program would have either
crashed or produced bizarre results, and then you'd be sitting there all
day trying to figure out why.
Oct 7 '05 #5
On 07 Oct 2005 17:53:50 GMT, in comp.lang.c , Dale <da***@gas.orange>
wrote:
"Davy" <zh*******@gmail.com> wrote in news:1128661915.425811.133260
@g44g2000cwa.googlegroups.com:

char x[4]={"my"};
Remember. sweetums, 'x' is a pointer when you declare it that way.


Actually, no, this is terribly terribly wrong. In neither declaration
is 'x' a pointer - its an array[4] of char.
If that assignment actually worked, it would be changing the pointer itself, not
the data that the pointer points to.


Which would be perfectly legal for a pointer. However for an array,
you simply can't do that.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Oct 7 '05 #6
You can use the following:
strcpy(x,"my");
instead of
x={"my"};

x is an array pointer not only a variable.

"Davy" <zh*******@gmail.com> ????
news:11**********************@g44g2000cwa.googlegr oups.com...
Hi all,

I found
char x[4]={"my"};
can be compiled.

But
char x[4];
x={"my"};
can not be compiled.

Why?
Any suggestions will be appreciated!

Best regards,
Davy

Oct 8 '05 #7
Mark McIntyre <ma**********@spamcop.net> wrote in
news:u8********************************@4ax.com:
On 07 Oct 2005 17:53:50 GMT, in comp.lang.c , Dale <da***@gas.orange>
wrote:
"Davy" <zh*******@gmail.com> wrote in news:1128661915.425811.133260
@g44g2000cwa.googlegroups.com:

char x[4]={"my"};


Remember. sweetums, 'x' is a pointer when you declare it that way.


Actually, no, this is terribly terribly wrong. In neither declaration
is 'x' a pointer - its an array[4] of char.


You're the one who's wrong, here, fucknut -- 'x' is a character pointer
when you declare it that way. That's how C stores an array in memory;
i.e., as a pointer to a chunk of RAM.

Run this little program and observe the output:

int main(void)
{

char x[4]={"my"};

printf("%c\n", x);
printf("%c\n", *x);

return 0;
}

The first printf() will display garbage (because it's actually printing
the value of a pointer) but the second will display the letter 'm'
(because it's printing the value that the pointer points to). If 'x'
were not a pointer then this wouldn't even fucking compile because '*x'
would be considered invalid indirection.

Dumbass.
Oct 8 '05 #8
Dale wrote:
Mark McIntyre <ma**********@spamcop.net> wrote in
news:u8********************************@4ax.com:

On 07 Oct 2005 17:53:50 GMT, in comp.lang.c , Dale <da***@gas.orange>
wrote:
"Davy" <zh*******@gmail.com> wrote in news:1128661915.425811.133260
@g44g2000cwa.googlegroups.com:

char x[4]={"my"};

Remember. sweetums, 'x' is a pointer when you declare it that way.
Actually, no, this is terribly terribly wrong. In neither declaration
is 'x' a pointer - its an array[4] of char.

You're the one who's wrong, here, fucknut -- 'x' is a character pointer


No x is an array
when you declare it that way. That's how C stores an array in memory;
i.e., as a pointer to a chunk of RAM.
That is just confused. Arrays are stored as 'a chunk of RAM', pointers
don't enter the picture.

Run this little program and observe the output:

int main(void)
{

char x[4]={"my"};

printf("%c\n", x);
printf("%c\n", *x);

return 0;
}

The first printf() will display garbage (because it's actually printing
the value of a pointer) but the second will display the letter 'm'
(because it's printing the value that the pointer points to). If 'x'
were not a pointer then this wouldn't even fucking compile because '*x'
would be considered invalid indirection.
You clearly don't know the rule in C and C++ which allows an array to
convert to a pointer in many cirumstances. x can convert to a pointer,
and that is what it is doing in both your examples above, but that does
not mean that x is a pointer.

Try this program out

int main()
{
char x[99];
printf("%u\n", sizeof x);
}

It x really was a pointer then that would print 4 (the size of a
pointer) but it prints 99 (the sizeof the array). That is because sizeof
is on of the exception to the rule that an array can be converted to a
pointer. There are other exceptions as well but they are rare, so I can
see how you might have missed this.

Dumbass.


If you are going to post to a public forum, you have accept the
possiblity that you might be wrong, and that you might be corrected. It
stops everyone else thinking you are a wanker if you can accept those
occaisions with good grace.

john
Oct 8 '05 #9
Dale <da***@gas.orange> writes:
Mark McIntyre <ma**********@spamcop.net> wrote in
news:u8********************************@4ax.com:
On 07 Oct 2005 17:53:50 GMT, in comp.lang.c , Dale <da***@gas.orange>
wrote:
"Davy" <zh*******@gmail.com> wrote in news:1128661915.425811.133260
@g44g2000cwa.googlegroups.com:

char x[4]={"my"};

Remember. sweetums, 'x' is a pointer when you declare it that way.
Actually, no, this is terribly terribly wrong. In neither declaration
is 'x' a pointer - its an array[4] of char.


You're the one who's wrong, here, fucknut -- 'x' is a character pointer
when you declare it that way. That's how C stores an array in memory;
i.e., as a pointer to a chunk of RAM.


Dale, let me offer some friendly advice.

First, don't be rude.

Second, don't be simultaneously rude and wrong.

Arrays are not pointers. Pointers are not arrays. An array is not
stored in memory as "a pointer to a chunk of RAM", it's stored in
memory as an array.

The declaration
char x[4];
declares an array object, with or without an initialization. It does
not declare a pointer object.

I think what's confused you is the fact that an array name, or any
expression of an array type, is implicitly converted to a pointer to
the array's first element in most contexts. (The exceptions are the
operand of the unary "&" or "sizeof" operator, and a string literal in
an initializer.)
Run this little program and observe the output:

int main(void)
{

char x[4]={"my"};

printf("%c\n", x);
printf("%c\n", *x);

return 0;
}

The first printf() will display garbage (because it's actually printing n
the value of a pointer) but the second will display the letter 'm'
(because it's printing the value that the pointer points to). If 'x'
were not a pointer then this wouldn't even fucking compile because '*x'
would be considered invalid indirection.
The first printf() invokes undefined behavior. The expression x,
which is of array type, is implicitly converted to a pointer value
of type char*. Passing this as an argument to printf() with a "%c"
format invokes undefined behavior. It happens to display garbage,
but since you're lying to the compiler it could do anything.

In the second printf(), the subexpression x is again converted to
a value of type char*. Dereferencing this pointer value yields the
character value 'm', so you're right about this one.

And of course you're missing the require "#include <stdio.h>, so
*any* call to printf() invokes undefined behavior. On many (most?)
implementations, it happens to work anyway, but you shouldn't count
on that.

The relationship between arrays and pointers is a common source of
confusion among C newbies. You need to read section 6, "Arrays and
Pointers", of the C FAQ (google "C FAQ" to find it). I see that this
thread is cross-posted to comp.lang.c and comp.lang.c++ (which is
rarely a good idea), but this happens to be an area where C and C++
are similar.
Dumbass.


There's a good chance that a lot of the regulars in these newsgroups
have already killfiled you, or will do so as soon as they see your
article. You may already have permanently damaged your ability to
participate here and to benefit from the advice of experts.

Be embarrassed.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Oct 8 '05 #10
Dale wrote:
Mark McIntyre <ma**********@spamcop.net> wrote in
news:u8********************************@4ax.com:
On 07 Oct 2005 17:53:50 GMT, in comp.lang.c , Dale <da***@gas.orange>
wrote:
"Davy" <zh*******@gmail.com> wrote in news:1128661915.425811.133260
@g44g2000cwa.googlegroups.com:

char x[4]={"my"};

Remember. sweetums, 'x' is a pointer when you declare it that way.


Actually, no, this is terribly terribly wrong. In neither declaration
is 'x' a pointer - its an array[4] of char.


You're the one who's wrong, here, fucknut -- 'x' is a character pointer
when you declare it that way. That's how C stores an array in memory;
i.e., as a pointer to a chunk of RAM.


I see that you have set the follow-ups to comp.lang.c. However, as your
original comment was posted in comp.lang.c++, too, be informed that, in the
context of C++, you are not correct with respect to the type of 'x'.
Consider:

#include <iostream>
#include <iomanip>
#include <typeinfo>

template < typename T >
struct is_array {

static const bool value = false;

};

template < typename T, unsigned long N >
struct is_array< T[N] > {

static const bool value = true;

};

template < typename T >
struct is_pointer {

static const bool value = false;

};

template < typename T >
struct is_pointer< T* > {

static const bool value = true;

};
int main ( void ) {
char x [4];

typedef char char_array [4];
char_array y;

typedef char* char_pointer;
char_pointer z;

std::cout << std::boolalpha << ( typeid(x) == typeid(y) ) << '\n';
std::cout << std::boolalpha << is_array<char_array>::value << '\n';
std::cout << std::boolalpha << is_pointer<char_array>::value << '\n';
std::cout << '\n';
std::cout << std::boolalpha << ( typeid(x) == typeid(z) ) << '\n';
std::cout << std::boolalpha << is_array<char_pointer>::value << '\n';
std::cout << std::boolalpha << is_pointer<char_pointer>::value << '\n';
}

This will print:
true
true
false

false
false
true
Maybe, you are correct within the context of the C programming language,
though.

Best

Kai-Uwe Bux
Oct 8 '05 #11
Dale wrote:
Mark McIntyre <ma**********@spamcop.net> wrote in
news:u8********************************@4ax.com:

On 07 Oct 2005 17:53:50 GMT, in comp.lang.c , Dale <da***@gas.orange>
wrote:
"Davy" <zh*******@gmail.com> wrote in news:1128661915.425811.133260
@g44g2000cwa.googlegroups.com:

char x[4]={"my"};

Remember. sweetums, 'x' is a pointer when you declare it that way.
Actually, no, this is terribly terribly wrong. In neither declaration
is 'x' a pointer - its an array[4] of char.

You're the one who's wrong, here, fucknut -- 'x' is a character pointer
when you declare it that way. That's how C stores an array in memory;
i.e., as a pointer to a chunk of RAM.

I'm afraid the fucknut is quite correct. A character pointer is not a
character array. An array can be implicitly converted to a pointer and
the [] construct can be applied to pointers, which is not the same thing.

If 'x' were only a character pointer, what memory is "my" being written
to? 'x' is a character array here. Go read the standard if you don't
believe it. Or read the FAQ. Specifically section 6:
http://www.eskimo.com/~scs/C-faq/s6.html

<snipped code where the implicit conversion from array to pointer is
demonstrated> Dumbass.


Pleased to meet you. Language aside, the courtesy of reading the FAQ of
a newsgroup you're posting to benefits all involved.

S.
Oct 8 '05 #12
Kai-Uwe Bux <jk********@gmx.net> writes:
Dale wrote:
Mark McIntyre <ma**********@spamcop.net> wrote in
news:u8********************************@4ax.com:
On 07 Oct 2005 17:53:50 GMT, in comp.lang.c , Dale <da***@gas.orange>
wrote:
"Davy" <zh*******@gmail.com> wrote in news:1128661915.425811.133260
@g44g2000cwa.googlegroups.com:
>
> char x[4]={"my"};

Remember. sweetums, 'x' is a pointer when you declare it that way.

Actually, no, this is terribly terribly wrong. In neither declaration
is 'x' a pointer - its an array[4] of char.
You're the one who's wrong, here, fucknut -- 'x' is a character pointer
when you declare it that way. That's how C stores an array in memory;
i.e., as a pointer to a chunk of RAM.


I see that you have set the follow-ups to comp.lang.c. However, as your
original comment was posted in comp.lang.c++, too, be informed that, in the
context of C++, you are not correct with respect to the type of 'x'.

[snip] Maybe, you are correct within the context of the C programming language,
though.


No, he's equally wrong in C.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Oct 8 '05 #13
Dale wrote:
Mark McIntyre <ma**********@spamcop.net> wrote in
news:u8********************************@4ax.com:
On 07 Oct 2005 17:53:50 GMT, in comp.lang.c , Dale <da***@gas.orange>
wrote:
"Davy" <zh*******@gmail.com> wrote in news:1128661915.425811.133260
@g44g2000cwa.googlegroups.com:

char x[4]={"my"};

Remember. sweetums, 'x' is a pointer when you declare it that way.
Actually, no, this is terribly terribly wrong. In neither declaration
is 'x' a pointer - its an array[4] of char.


You're the one who's wrong,


No is isn't.
here, fucknut
why resort to abuse? All it does is make *you* look bad and probably
make at least some of the knowledgeable people around here plonk you
reducing the chance of you getting useful help when you need it.
-- 'x' is a character pointer
when you declare it that way.
No, x is an array of char. Try checking any decent book on C (or C++) or
the comp.lang.c FAQ or the standard or any of the times this has been
discussed before.
That's how C stores an array in memory;
i.e., as a pointer to a chunk of RAM.
No. If it was a pointer you could assign to x, but every conforming
compiler will diagnose it as an error.
Run this little program and observe the output:

int main(void)
{

char x[4]={"my"};

printf("%c\n", x);
printf("%c\n", *x);

return 0;
}

The first printf() will display garbage (because it's actually printing
the value of a pointer)
No, it might do anything because an array decays to a pointer to its
first element in this situation and that is not what you have said you
will print.
but the second will display the letter 'm'
(because it's printing the value that the pointer points to). If 'x'
were not a pointer then this wouldn't even fucking compile because '*x'
would be considered invalid indirection.
No, it compiles because this is one of the many situations in which an
array will decay to a pointer to the first element.
Dumbass.


That description would appear to apply to you, not Mark. I suggest you
try actually learning the language before claiming people are wrong and
insulting them.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Oct 8 '05 #14
Dale wrote:
Mark McIntyre <ma**********@spamcop.net> wrote in
news:u8********************************@4ax.com:
On 07 Oct 2005 17:53:50 GMT, in comp.lang.c , Dale <da***@gas.orange>
wrote:
"Davy" <zh*******@gmail.com> wrote in news:1128661915.425811.133260
@g44g2000cwa.googlegroups.com:

char x[4]={"my"};

Remember. sweetums, 'x' is a pointer when you declare it that way.
Actually, no, this is terribly terribly wrong. In neither declaration
is 'x' a pointer - its an array[4] of char.

You're the one who's wrong, here, fucknut -- 'x' is a character pointer
when you declare it that way. That's how C stores an array in memory;
i.e., as a pointer to a chunk of RAM.


Just because you are completely wrong does not mean that you must use
abusive language. Cursing at Mark will not make your cluelessness
suddenly appear to be enlightenment. In
char x[4] = {"x");
x is an array of char, not a pointer, and only the as yet still ignorant
think otherwise. When the ignorant loudly declare their ignorance to be
truth, as you did, that correctable ignorance is transformed into
stubborn and boorish stupidity.

Run this little program and observe the output:
Don't bother.
To start with, the variadic function printf() requires a declaration in
scope. Dale, who properly signs himself below as "Dumbass", left this out.

int main(void)
{

char x[4]={"my"};

printf("%c\n", x);
As everyone but Dale who styles himself "Dumbass" knows, when an array
is passed as an argument, the value passed is a pointer to the beginning
of that array. Nothing constructive can be said about whether x is an
array or not can be said from a situation in which a pointer is passed
whether x is an array or a pointer. We can, however, say that anyone
who thinks he could pass either an array or a pointer to printf and
expect anything meaningful from the absurd use of the "%c" specifier
should not be giving lessons to anyone. He needs to be rereading the
more elementary parts of his C text instead.
printf("%c\n", *x);

return 0;
}

The first printf() will display garbage (because it's actually printing
the value of a pointer) but the second will display the letter 'm'
(because it's printing the value that the pointer points to). If 'x'
were not a pointer then this wouldn't even fucking compile because '*x'
would be considered invalid indirection.
We already know that the above argument is garbage. What Dale perhaps
should look at (extra brackets retained)
is:
#include <stdio.h>

int main(void)
{

char x[] = { "The array named 'x' has this." };
char *y = { "The pointer named 'y' points to this." };

printf("The array x (\"%s\") has size %lu\n", x,
(unsigned long) sizeof(x));
printf("The pointer y (\"%s\") has size %lu\n", y,
(unsigned long) sizeof(y));

return 0;
}
[Output for this implementation]
The array x ("The array named 'x' has this.") has size 30
The pointer y ("The pointer named 'y' points to this.") has size 4

Dumbass.


If you want to use a .sig, remember to place the .sig separator before it.
Oct 8 '05 #15
Dale wrote:

You're the one who's wrong, here, fucknut -- 'x' is a character
pointer when you declare it that way. That's how C stores an array
in memory; i.e., as a pointer to a chunk of RAM.

Besides being dead wrong, you're a jerk. So it's a quick plonk for you.

Brian
Oct 8 '05 #16
On 08 Oct 2005 19:26:59 GMT, in comp.lang.c , Dale <da***@gas.orange>
wrote:
Mark McIntyre <ma**********@spamcop.net> wrote in
news:u8********************************@4ax.com :
Actually, no, this is terribly terribly wrong. In neither declaration
is 'x' a pointer - its an array[4] of char.
You're the one who's wrong, here, fucknut


You're amusingly wrong, as well as abusive. Arrays are not pointers.
Run this little program and observe the output:
(program which passes an array and its first element to printf())

Which proves nothing. When passed to a function, an array argument
decays into a pointer to its first element. Please read the FAQ (6.3
onwards I believe) and the ISO standard if you need more detail,

Anyway, if we're writing test cases, try this one:

#include <stdio.h>
int main(void)
{
int x[365];
return printf("%d %d\n", sizeof(x), sizeof(*x));
}

And then ask yourself how large the pointers are on your system...
The first printf() will display garbage (because it's actually printing
the value of a pointer)
well, actually it prints garbage because %c and array[4] of int are
incompatible, and you've invoked undefined behaviour.
Dumbass.


Physician, heal thyself.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Oct 8 '05 #17
On Sat, 08 Oct 2005 22:32:20 +0200, in comp.lang.c , Skarmander
<in*****@dontmailme.com> wrote:
Dale wrote:
Mark McIntyre <ma**********@spamcop.net> wrote in
Actually, no, this is terribly terribly wrong. In neither declaration
is 'x' a pointer - its an array[4] of char.

You're the one who's wrong, here, fucknut --

I'm afraid the fucknut is quite correct.


Whoy, I resemble that remark!
:-)

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Oct 8 '05 #18
On 7 Oct 2005 06:02:00 -0700, "werasm" <w_*****@telkomsa.net> wrote in
comp.lang.c:

Davy wrote:
Hi all,

I found
char x[4]={"my"};
can be compiled.
Yes, but it is better to do this:

char x[] = "my";

This way just enough space for "my" is provided.
But
char x[4];
x={"my"};
can not be compiled.


Because the type of x in...

char x[4];

...is effectively...

char* const x;


No, it is not. 'x' is not a pointer, not any kind of pointer to
anything.
...which means the value of the pointer "x" is constant - may not be
modified, whereas doing this...
The statement above has no meaning, since there is no 'pointer "x"'.
x={"my"}; //- actually x = "my"...

...attemps to modify the pointer x, which is why you get a compiler
error.
Except that, once again, there is no 'pointer x'. 'x' is the name of
a region of storage that is large enough to store four chars. There
is no pointer involved.
Suggestions as follow:

char x[100] = { '\0' };
std::ostrstream os( x, sizeof(x) );
os << "Hooh, hah" << std::ends; //don't forget std::ends;

or...

std::string x("my");

or...

char x[4] = { '\0' };
strcpy( x, "my" );

Remember, the contents of the array which exists at the address
location whereto x points, is modifiable. The address itself (or the
But 'x' does not point to anything.
value of the ptr) is not.
There is no 'ptr' (sic).
Regards,

W


It is posts like this that help keep the confusion about arrays and
pointers worse than it has to be.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Oct 9 '05 #19
> No, it is not. 'x' is not a pointer, not any kind of pointer to
anything.


Hi Jack,

According to Bjarne Stroustrup:

"The name of an array can be used as a pointer to its initial element."

In my own words - "The name of an array is implicitly convertable to a
pointer pointing to the address location of its first element..."

While I do understand that x is in actual fact "the name of a region
that is large enough to store four chars" - or simply the name of an
array of characters of for elements, my point remains that, in contrast
to this case...

char* x = new char[4];

.... the type of x in case...

char x[4];

....is very similar (or effectively the same as) to...

char* const x = new char[4];

I did not say exactly the same (or equivalent to) - but reacts the same
in that one cannot do this:

char* const x( 0 );
char* y( new char [4] );
x = y;

Which would help (I hope) the initial poster to understand it a little
better (IMHO) - especially the reason for his compilation error.
It is posts like this that help keep the confusion about arrays and
pointers worse than it has to be.


I disagree with this. The fact that the type <char[4]> is implicitly
convertable ot <char*> is confusing. Using my explanation, I attempt to
clarify it to c++ users that find it confusing. If you feel that I've
failed to do so (clarify), suit yourself.

Thank you for your response anyway. Agreed - but my posting was misread
by you - I feel.

Regards,

W

Oct 10 '05 #20
"werasm" <w_*****@telkomsa.net> writes:
No, it is not. 'x' is not a pointer, not any kind of pointer to
anything.
Hi Jack,

According to Bjarne Stroustrup:

"The name of an array can be used as a pointer to its initial element."

In my own words - "The name of an array is implicitly convertable to a
pointer pointing to the address location of its first element..."


Yes, in most contexts.
While I do understand that x is in actual fact "the name of a region
that is large enough to store four chars" - or simply the name of an
array of characters of for elements, my point remains that, in contrast
to this case...

char* x = new char[4];

... the type of x in case...

char x[4];

...is very similar (or effectively the same as) to...

char* const x = new char[4];

I did not say exactly the same (or equivalent to) - but reacts the same
in that one cannot do this:

char* const x( 0 );
char* y( new char [4] );
x = y;

Which would help (I hope) the initial poster to understand it a little
better (IMHO) - especially the reason for his compilation error.


Note that this thread is (unwisely) cross-posted to comp.lang.c and
comp.lang.c++. The C equivalent of "new char[4]" would be "malloc(4)"
(there are probably some subtle differences).

Saying that an array declaration is equivalent to a pointer
declaration is *exactly* what makes this area so confusing.
Attempting to view it that way makes it very difficult to understand
why sizeof(x) doesn't give you the size of the array, or why &x
doesn't give you the address of a pointer.

On the other hand, all these things follow naturally from an
understanding of what's really going on.

Namely:

Arrays are arrays. Pointers are pointers. They are not the same
thing; an array declaration creates an array object, *not* a pointer
object.

An expression of array type, in most contexts, is implicitly converted
to a pointer to the array's first element. This does not apply to the
operand of a unary "&" or "sizeof" operator, or to a string literal in
an initializer.

In addition (and somewhat confusingly), a function parameter declared
with what appears to be an array type is really of a pointer type.
This does *not* follow from other rules; it's an explicit special
case.

Finally, read section 6 of the C FAQ. (There's probably similar
information in the C++ FAQ.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Oct 10 '05 #21

Keith Thompson wrote:
Note that this thread is (unwisely) cross-posted to comp.lang.c and
comp.lang.c++. The C equivalent of "new char[4]" would be "malloc(4)"
(there are probably some subtle differences).
I don't really read comp.lang.c, therefore would not be aware of cross
posting. Yes, I know that C equivalent is malloc(4). I don't want to
debate these differences.
An expression of array type, in most contexts, is implicitly converted
to a pointer to the array's first element. This does not apply to the
operand of a unary "&" or "sizeof" operator, or to a string literal in
an initializer.
Yes, agreed - especially wrt. the "does not apply to" part, and well
said. Furthermore, you cannot assign <char*> type to char[] type. In
this respect, char[] type is similar to <char* const> type - similar,
not equivalent. I agree that mentioning it may be confusing.
In addition (and somewhat confusingly), a function parameter declared
with what appears to be an array type is really of a pointer type.
Yes, this I'm aware of - that is why it is a good idea to use a boost
array instead as argument - or a vector, where the type is more
explicit if your size is not known at compile time. In "C", I suppose
one would use, when working with arrays something to the effect of:

void foo( char[] array, unsigned sz );
This does *not* follow from other rules; it's an explicit special
case.


....and has been the root of many problems.

I have scanned the C++ FAQ's but could find anything of the cuff. I
personally have no problem with this. I'm in agreeance with what you've
said. Also with the way in which you have said it.

Thank you and kind regards,

W

Oct 10 '05 #22
werasm wrote:
No, it is not. 'x' is not a pointer, not any kind of pointer to
anything.


Hi Jack,

According to Bjarne Stroustrup:

"The name of an array can be used as a pointer to its initial element."

In my own words - "The name of an array is implicitly convertable to a
pointer pointing to the address location of its first element..."

While I do understand that x is in actual fact "the name of a region
that is large enough to store four chars" - or simply the name of an
array of characters of for elements, my point remains that, in contrast
to this case...

char* x = new char[4];

... the type of x in case...

char x[4];

...is very similar (or effectively the same as) to...

char* const x = new char[4];


Well. I see where you are heading at, but yet this is not true. The type
is convertible, but that's all. So whenever the compiler has an array[] type
and there is need to convert, eg. because a function accepts a pointer, the
compiler can do this under the hood. But never say: *an array is a pointer*
or varitions of that, since it is plain wrong.

eg.

abcd.h
******

char foo[] = { "hello" }; // declare an array

defgh.cpp
*********
#include <stdio.h>

extern char* foo;

int main()
{
printf( "%s", foo );
}

this will fail without a doubt for exactly that reason: an array is not a pointer,
not even close. But: In some cicumstances an array can act 'as if it were' a pointer.
AFAIK there were 2 resons for this:
* passing arrays to functions which K&R felt to not be necessary and thereby bypassing the
problem of what to do with non matching array sizes (that especially would have been a
problem with some character arrays acting as string storage).
* Array indexing is defined in terms of pointer arithmetic.
a[i] is equivalent to *(a+i)
(a beeing an array and i beeing an index).

Especially the last point is the explanation, why one can do:

char c = malloc(4);
c[3] = '\0';

The compiler immediatly transforms this to
*(c+3)
and applies the usual pointer arithmetic.
Doing the same with an array

char d[4];
d[3] = '\0'

again: The compiler transforms this into
*(d+3) = '\0'

and now the array to pointer conversion kicks in, and converts the array
to a pointer to its first element. Then the usual array arithmetic can be done.

But even if both versions look equivalent on the C source code level (or C++), the
generated machine code is usually different.

*(c+3) is converted to ( c beeing a 'real pointer')

fetch value for c
add 3
assign '\0' to that memory address

*(d+3) translates to:

load address of d
add 3
assign '\0' to that memory address

NB: If you have sorted out this issue with a newbie :-) there is an easy way
to further confuse him. Introduce him to

char e[4];
3[e] = '\0';

and ask if it is valid and if yes, why?

--
Karl Heinz Buchegger
kb******@gascad.at
Oct 10 '05 #23

Keith Thompson wrote:
Finally, read section 6 of the C FAQ. (There's probably similar
information in the C++ FAQ.)


Have done so (now). You've quoted it almost exactly (if not).

I also noticed in (6.9) that my explanation have been used in the past
as simplification. I wonder why ;-). People crawl before they walk.

When I still tried to understand what a pointer was (I have read many
definitions by now), I conceptualized it by reading a decription
stating that "a pointer is an integer whos value is an address". On
other occasions(much later), I was actually corrected when considering
a pointer as an integer. The fact remains that the original description
contributed to my understanding of pointers. Likewise, I do think that
my explanation contributes to understanding the reason why the original
posters problem did not compile. Whether you agree or not, this opinion
remains. I nevertheless appreciated your comments and references.

Kind regards,

W

Oct 10 '05 #24

Karl Heinz Buchegger wrote:
abcd.h
******

char foo[] = { "hello" }; // declare an array

defgh.cpp
*********
#include <stdio.h>

extern char* foo;

int main()
{
printf( "%s", foo );
}

this will fail without a doubt for exactly that reason: an array is not a pointer,
not even close. But: In some cicumstances an array can act 'as if it were' a pointer.
I absolutely agree :). Have always.
But even if both versions look equivalent on the C source code level (or C++), the
generated machine code is usually different.

*(c+3) is converted to ( c beeing a 'real pointer')

fetch value for c
add 3
assign '\0' to that memory address

*(d+3) translates to:

load address of d
add 3
assign '\0' to that memory address
Interesting...
char e[4];
3[e] = '\0';

and ask if it is valid and if yes, why?


Yes, it is valid - because "array subscripting is commutive in C
(...and C++?)". Not common practice though, and you don't have to
consider yourself a newbie if you don't use (or did not know) this. In
fact, I've never come accross this in real code :-) (code obfuscation
.... bad).

Also, the term newbie is relative... Maybe always considering oneself a
newbie is not a bad thing - at least your learn. Ditto for posting
answers to newbies. Our swearing friend (Dale) could learn from this.

Also, I suppose reading the FAQ's before posting the original question
would have been desirable.

Regards,

W

Oct 10 '05 #25
werasm wrote:
Keith Thompson wrote:
Finally, read section 6 of the C FAQ. (There's probably similar
information in the C++ FAQ.)
Have done so (now). You've quoted it almost exactly (if not).

I also noticed in (6.9) that my explanation have been used in the past
as simplification. I wonder why ;-). People crawl before they walk.

When I still tried to understand what a pointer was (I have read many
definitions by now), I conceptualized it by reading a decription
stating that "a pointer is an integer whos value is an address". On
other occasions(much later), I was actually corrected when considering
a pointer as an integer.


An easy way (in my opinion) to conceptualise a pointer is it is like
your finger. It might be pointing at a piece of paper where you scrawled
a number (directing you to read a number from the piece of paper when
you dereference it) or if it is a wild pointer it might be pointing in
to the wild blue yonder (there was a piece of paper with a number, but
it was incinerated when you freed it) or it might be a null pointer
which means it is not pointing anywhere.

Incrementing a pointer is then just moving your finger to point at the
next number on that piece of paper (array or allocated block) and then
it is obvious that you hit problems when you go passed the edge of the
paper.
The fact remains that the original description
contributed to my understanding of pointers. Likewise, I do think that
my explanation contributes to understanding the reason why the original
posters problem did not compile. Whether you agree or not, this opinion
remains. I nevertheless appreciated your comments and references.


I've not read your original description (or not recently enough to
remember it) so I can't comment directly on it. However, if Kieth
pointed out problems in it then you should listen to him since he knows
what he is talking about.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Oct 10 '05 #26

Flash Gordon wrote:
An easy way (in my opinion) to conceptualise a pointer is it is like
your finger.


I don't need to conceptualise a pointer anymore :-). That was not the
point. Read all before you comment.

Regards,

W

Oct 10 '05 #27
On Sat, 08 Oct 2005 22:34:09 +0100, Flash Gordon
<sp**@flash-gordon.me.uk> wrote:
Dale wrote:


<snip: arrays are not pointers, at some length, correctly>
> That's how C stores an array in memory;
i.e., as a pointer to a chunk of RAM.


No. If it was a pointer you could assign to x, but every conforming
compiler will diagnose it as an error.

If as he wrongly claimed an array was a const pointer, you would get a
required diagnostic if you try to assign to it. It in fact _isn't_ a
pointer, but inability to assign isn't in itself evidence of that.

- David.Thompson1 at worldnet.att.net
Oct 17 '05 #28
On Mon, 10 Oct 2005 09:42:42 GMT, Keith Thompson <ks***@mib.org>
wrote:
"werasm" <w_*****@telkomsa.net> writes: <snip: C++ example> Note that this thread is (unwisely) cross-posted to comp.lang.c and
comp.lang.c++. The C equivalent of "new char[4]" would be "malloc(4)"
(there are probably some subtle differences).
I'm not sure I agree. The (unusual) array-pointer relationship is one
of the areas where C++ _does_ remain fully compatible with C. C++ does
provide often preferable alternatives for some uses of arrays, but
none of them are under discussion here.

<snip> An expression of array type, in most contexts, is implicitly converted
to a pointer to the array's first element. This does not apply to the
operand of a unary "&" or "sizeof" operator, or to a string literal in
an initializer.

For completeness: or in C++ as the operand of typeid. Or officially as
the initializer for a reference (to array) or argument to such a
parameter; of course in practice references are implemented as
(hidden, protected) pointers.

- David.Thompson1 at worldnet.att.net
Oct 17 '05 #29

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Forecast | last post by:
I run the following code in UNIX compiled by g++ 3.3.2 successfully. : // proj2.cc: returns a dynamic vector and prints out at main~~ : // : #include <iostream> : #include <vector> : : using...
17
by: Olivier Bellemare | last post by:
I've tried to make a function that returns the middle of a string. For example: strmid("this is a text",6,4); would return "is a". Here is my code: char *strmid(char *texte, int depart,...
51
by: Alan | last post by:
hi all, I want to define a constant length string, say 4 then in a function at some time, I want to set the string to a constant value, say a below is my code but it fails what is the correct...
18
by: Steve Litvack | last post by:
Hello, I have built an XMLDocument object instance and I get the following string when I examine the InnerXml property: <?xml version=\"1.0\"?><ROOT><UserData UserID=\"2282\"><Tag1...
32
by: tshad | last post by:
Can you do a search for more that one string in another string? Something like: someString.IndexOf("something1","something2","something3",0) or would you have to do something like: if...
12
by: Jeff S | last post by:
In a VB.NET code behind module, I build a string for a link that points to a JavaScript function. The two lines of code below show what is relevant. PopupLink = "javascript:PopUpWindow(" &...
4
by: MooMaster | last post by:
After some google searching on the forum I couldn't find any topics that seemed to relate exactly to my problem, so hopefully someone can help me out... I'm running python 2.4.1 on a local Win2K...
6
by: tommaso.gastaldi | last post by:
Hi, does anybody know a speedy analog of IsNumeric() to check for strings/chars. I would like to check if an Object can be treated as a string before using a Cstr(), clearly avoiding the time...
5
by: ThatVBGuy | last post by:
Hello All, I could really use some help with this problem its driving me nuts. I have a small vb app, the goal of the app is to read an html doc into a variable then go through that variable and...
1
Atli
by: Atli | last post by:
The following small HowTo is a compilation of an original problem in getting some cookie-values through different methods of string-handling. The original Problem was posted as follows: As...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.