473,790 Members | 3,185 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
28 2131
"werasm" <w_*****@telkom sa.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_Keit h) 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.ne t
Oct 17 '05 #28
On Mon, 10 Oct 2005 09:42:42 GMT, Keith Thompson <ks***@mib.or g>
wrote:
"werasm" <w_*****@telkom sa.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.ne t
Oct 17 '05 #29

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

Similar topics

7
10629
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 namespace std; : : vector<string>* getTyphoon()
17
14363
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, int longueur) { char *resultat = " "; char *temporaire = " "; int nbr;
51
8298
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 code? many thx!
18
7198
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 QID=\"55111\"><Tag2 AID=\"5511101\"></Tag2></Tag1><Tag1 QID=\"55112\"><Tag2 AID=\"5511217\"></Tag2></Tag1><Tag1 QID=\"5512282\"><Tag2 AID=\"551228206\"></Tag2></Tag1><Tag1 QID=\"55114\"><Tag2 AID=\"5511406\"></Tag2></Tag1><Tag1 QID=\"55115\"><Tag2
32
14902
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 ((someString.IndexOf("something1",0) >= 0) || ((someString.IndexOf("something2",0) >= 0) ||
12
9646
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(" & Chr(34) & PopUpWindowTitle & Chr(34) & ", " & Chr(34) & CurrentEventDetails & ")" strTemp += "<BR><A HREF='#' onClick='" & PopupLink & "'>" & EventName & "</A><BR>" The problem I have is that when the string variables or contain a string with an...
4
5281
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 system and doing some work-related development on an AIX box, and I'm running into a problem using cx_Oracle to add some information to an Oracle 9.2 table. I have a table_title defined as a VARCHAR2 data type, and when I'm trying to retrieve...
6
2215
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 and resource consuming Try... Catch, which in iterative processing is totally unacceptable. -tom
5
3537
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 find and replace some tags. I have 3 functions. 1 to open the doc, the 2nd to find and replace the tags the 3rd to save the info. the code is pasted below : Public Function ReadFileContents(FileFullPath As String) As _ String On Error GoTo...
1
8378
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 you can see, there could have been a problem with the split-method. The following short article handles ways around this possible problem, that we couldn't reproduce, but someone may possibly encounter it too sometimes. If nothing else, the shown...
0
9666
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9512
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10419
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9987
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9023
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7531
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5424
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5552
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4100
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.