473,779 Members | 2,062 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 #1
28 2129
In article <11************ **********@g44g 2000cwa.googleg roups.com>,
Davy <zh*******@gmai l.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-hyperdimensiona l 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*******@gmai l.com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.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*******@gmai l.com> wrote in news:1128661915 .425811.133260
@g44g2000cwa.go oglegroups.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.oran ge>
wrote:
"Davy" <zh*******@gmai l.com> wrote in news:1128661915 .425811.133260
@g44g2000cwa.g ooglegroups.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*******@gmai l.com> ????
news:11******** **************@ g44g2000cwa.goo glegroups.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**********@s pamcop.net> wrote in
news:u8******** *************** *********@4ax.c om:
On 07 Oct 2005 17:53:50 GMT, in comp.lang.c , Dale <da***@gas.oran ge>
wrote:
"Davy" <zh*******@gmai l.com> wrote in news:1128661915 .425811.133260
@g44g2000cwa. googlegroups.co m:

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**********@s pamcop.net> wrote in
news:u8******** *************** *********@4ax.c om:

On 07 Oct 2005 17:53:50 GMT, in comp.lang.c , Dale <da***@gas.oran ge>
wrote:
"Davy" <zh*******@gmai l.com> wrote in news:1128661915 .425811.133260
@g44g2000cwa .googlegroups.c om:

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.oran ge> writes:
Mark McIntyre <ma**********@s pamcop.net> wrote in
news:u8******** *************** *********@4ax.c om:
On 07 Oct 2005 17:53:50 GMT, in comp.lang.c , Dale <da***@gas.oran ge>
wrote:
"Davy" <zh*******@gmai l.com> wrote in news:1128661915 .425811.133260
@g44g2000cwa .googlegroups.c om:

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_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 8 '05 #10

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
8296
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
14898
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
9645
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
5279
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
2214
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
3536
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
8376
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
9636
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
9474
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
10306
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
10138
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9930
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...
1
7485
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
5503
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3632
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2869
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.