473,657 Members | 2,528 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What type is x in "char x[2];"?

I thought that:

char x[2];

made x into a pointer-to-char.

But how come the following code won't compile:

int main() {
char pbuf[2];
pbuf[0] = 'a';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;

pbuf = new char[2]; //Lvalue Required ERROR
pbuf[0] = 'b';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;
delete[] pbuf;

return 0;
}

In contrast, the following code compiles and runs as expected:

int main() {
char *pbuf;
pbuf = new char[2];
pbuf[0] = 'a';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;
delete[] pbuf;

pbuf = new char[2];
pbuf[0] = 'b';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;
delete[] pbuf;

return 0;
}

Why won't the first example work?

Thanks,
cpp
Jul 22 '05 #1
16 2146

"cppaddict" <he***@hello.co m> wrote in message
news:k3******** *************** *********@4ax.c om...
I thought that:

char x[2];

made x into a pointer-to-char.
No. 'x' is an array.

An array is not a pointer.
A pointer is not an array.

But how come the following code won't compile:

#include <iostream> /* for std::cout */
#include <ostream> /* for std::endl */
int main() {
char pbuf[2];
pbuf[0] = 'a';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;

pbuf = new char[2]; //Lvalue Required ERROR
You Can't Do That. Arrays cannot be assigned to like that.
Only each individual element can be assigned.

Again, an array is not a pointer. A pointer is not an array.
I thought you'd been posting and reading here long enough
to know that by now. :-)
pbuf[0] = 'b';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;
delete[] pbuf;

return 0;
}

In contrast, the following code compiles and runs as expected:
Yes, because 'pbuf' is a pointer, to which you can assign
a value.

#include <iostream> /* for std::cout */
#include <ostream> /* for std::endl */
int main() {
char *pbuf;
pbuf = new char[2];
pbuf[0] = 'a';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;
delete[] pbuf;

pbuf = new char[2];
pbuf[0] = 'b';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;
delete[] pbuf;

return 0;
}

Why won't the first example work?


Because an array is not a pointer. Because arrays cannot
be assigned to. Because the return type of operator 'new'
is a pointer, so even if you could assign to an array,
it's the wrong type (it's not a pointer).

-Mike
Jul 22 '05 #2
cppaddict wrote:
I thought that:

char x[2];

made x into a pointer-to-char.
...


No, 'x' here is of type 'char[2]'. The rest follows.

--
Best regards,
Andrey Tarasevich

Jul 22 '05 #3
#include <iostream> /* for std::cout */
#include <ostream> /* for std::endl */
Already had those. Just weren't in the post...
Again, an array is not a pointer. A pointer is not an array.
I thought you'd been posting and reading here long enough
to know that by now. :-)


Indeed. I should have. I'm a little embarrassed, but my confusion
comes from some semi-legitimate sources. First, the fact that you can
do pointer arithmetic with arrays. For example, the following prints
b:

int main() {
char pbuf[2];
pbuf[0] = 'a';
pbuf[1] = 'b';
pbuf[2] = '\0';
std::cout << *(pbuf+1);

return 0;
}

This makes it seem like a pointer. Also, I've been working with the
Windows API, which often makes pointers and arrays seem
interchangeable . For example, consider this code for retrieving a
line from a Rich Edit control:

char pbuf[100];
pbuf[99] = '\0';
pbuf[0] = 99 //specifies max number of characters to retrieve;
SendMessage(hwn dRichEdit,EM_GE TLINE,0,(LPARAM )pbuf);
std::cout << "Line 1: " << pbuf << std::endl;

which works. The LPARAM is of type pointer I'm pretty sure. The docs
are here:

http://msdn.microsoft.com/library/de...em_getline.asp

Can you explain why the above two things work even though pointers and
arrays of different types?

Thanks,
cpp

Jul 22 '05 #4

"cppaddict" <he***@hello.co m> wrote in message
news:o2******** *************** *********@4ax.c om...
#include <iostream> /* for std::cout */
#include <ostream> /* for std::endl */
Already had those. Just weren't in the post...
Again, an array is not a pointer. A pointer is not an array.
I thought you'd been posting and reading here long enough
to know that by now. :-)


Indeed. I should have. I'm a little embarrassed, but my confusion
comes from some semi-legitimate sources. First, the fact that you can
do pointer arithmetic with arrays. For example, the following prints
b:

int main() {
char pbuf[2];
pbuf[0] = 'a';
pbuf[1] = 'b';
pbuf[2] = '\0';
std::cout << *(pbuf+1);

return 0;
}

This makes it seem like a pointer. Also, I've been working with the
Windows API, which often makes pointers and arrays seem
interchangeable . For example, consider this code for retrieving a
line from a Rich Edit control:

char pbuf[100];
pbuf[99] = '\0';
pbuf[0] = 99 //specifies max number of characters to retrieve;
SendMessage(hwn dRichEdit,EM_GE TLINE,0,(LPARAM )pbuf);
std::cout << "Line 1: " << pbuf << std::endl;

which works. The LPARAM is of type pointer I'm pretty sure. The docs
are here:

http://msdn.microsoft.com/library/de...em_getline.asp

Can you explain why the above two things work even though pointers and
arrays of different types?


It works because when an array is passed to a function it decays to a
pointer to its first element.
Thanks,
cpp


/ WP
Jul 22 '05 #5
char x[2];
means x is a charachter array of size 2 .
x is kind of a constant pointer and hence you cannot dynamically
point x to some other memory location.
whereas char *px; means px is a pointer to charachter, since it is not
constant you can dynamically make it point to any new memory location
allocated with new char[]

Hope this helps.

Sohail
Jul 22 '05 #6
cppaddict <he***@hello.co m> wrote in message news:<k3******* *************** **********@4ax. com>...
I thought that:

char x[2];

made x into a pointer-to-char.
No -- this defines x as an array of char.
But how come the following code won't compile:

int main() {
char pbuf[2];
pbuf[0] = 'a';
pbuf[1] = '\0';
std::cout << pbuf << std::endl;

pbuf = new char[2]; //Lvalue Required ERROR
Because an array isn't a (modifiable) lvalue.

[ ... ]
Why won't the first example work?


Your code is ill-formed because your understanding about x was
incorrect.

As you've defined it above, x is an array. If you were to pass x as a
parameter to a function, then what would be passed would be a pointer
to the beginning of the array, but here you're not passing it as a
parameter. As it stands right now, you're trying to assign to x which
is an array, and assigning to an array simply isn't allowed.

Note that as a parameter, what you get is a pointer even if you use
array-style notation in the function declaration/definition. For
example:

void f(char x[2]) {
// This is well-formed code. The '2' above is entirely ignored
// so we can assign a pointer to a larger array, such as:
x = new char[20];
}

You can argue (and I'd agree) that this is usually a bad idea, but the
compiler won't do a thing to stop it. If you're feeling particularly
ornery, you can even do something like:

void f(char x[2]);
void f(char *x) { }

and get away with it -- at least with the compiler. Of course, if any
of your co-workers find out, it's your problem, not mine! :-)

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 22 '05 #7
char pbuf[2];
is an array. An array is NOT same as a pointer.
It means the address the array points to is a constant, it cannot be changed.
Hence
pbuf = new char[2];
is WRONG

In this
char *pbuf;
pbuf is NOT an array, it is a pointer so its address can be changed.
Hence
pbuf = new char[2];
works fine.

hth
david michell
Jul 22 '05 #8
Le lundi 30 août 2004 à 06:03, cppaddict a écrit dans comp.lang.c++*:
char pbuf[2];
pbuf[0] = 'a';
pbuf[1] = 'b';
pbuf[2] = '\0';


Now, wait a minute! You declare an array of two, then assign three
elements...

--
___________ 2004-08-30 11:00:46
_/ _ \_`_`_`_) Serge PACCALIN -- sp ad mailclub.net
\ \_L_) Il faut donc que les hommes commencent
-'(__) par n'être pas fanatiques pour mériter
_/___(_) la tolérance. -- Voltaire, 1763
Jul 22 '05 #9
cppaddict wrote:


Can you explain why the above two things work even though pointers and
arrays of different types?


You need to distinguish between what things *are* and how things are
*used*

If the name of an array is used without an indexing operation (*), then the
name of the array decays into a pointer to its first element. But note:
The name is still not a pointer, it is just used as if it were one.

Heck. Even array indexing is defined in terms of pointer operations:

char b[10];

b[5] is identical to *(b+5) by definition
(*) with sizeof beeing one exception that comes to my mind immediatly

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #10

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

Similar topics

5
21663
by: Ernez Catovic | last post by:
Please help me. I can see the content of field type CHAR(n) FOR BIT DATA of DB2 database, but when I try to see the content of mentioned field type by using SQL query (ODBC connection) only I can see are some digits, instead of appropriate characters.
4
10687
by: John Devereux | last post by:
Hi, I would like some advice on whether I should be using plain "chars" for strings. I have instead been using "unsigned char" in my code (for embedded systems). In general the strings contain ASCII characters in the 0-127 range, although I had thought that I might want to use the 128-255 range for special symbols or foreign character codes. This all worked OK for a long time, but a recent update to the compiler on my system has...
12
5502
by: arkobose | last post by:
my earlier post titled: "How to input strings of any lengths into arrays of type: char *array ?" seems to have created a confusion. therefore i paraphrase my problem below. consider the following program: #include<stdio.h> #define SIZE 1 int main()
1
2813
by: VM | last post by:
How would I need to call MessageBox.Show() so it displays a variable of type char of 9 chars (char) ? If I use it normally (MessageBox.Show (myVar.ToString()); ), it displays System.Char. Thanks.
5
14095
by: Omats.Z | last post by:
what is meaning os "char **option meet"? I get a function like this: __________________________________ int getchoice(char *greet, char *choices) { int chosen = 0; int selected; char **option; // what is this line mean? do { printf("Choice: %s\n", greet);
20
3538
by: liujiaping | last post by:
I'm confused about the program below: int main(int argc, char* argv) { char str1 = "abc"; char str2 = "abc"; const char str3 = "abc"; const char str4 = "abc"; const char* str5 = "abc";
14
307
by: Anna | last post by:
I try to put 8 int bit for example 10100010 into one character of type char(1 octet) with no hope . Could anyone propose a simple way to do it? Thank you very much.
4
2383
by: prasad8619 | last post by:
please help me out in this regard as this is urgent to me because i stuck in the middle of a program....... here I have a program like this...... char name="rajesh"; char *x=strchr(name,"j"); int k =strlen(name); int i=x-name; int p=k-i;
0
8425
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
8326
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
8743
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...
1
8522
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6177
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
5647
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4173
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
4333
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1736
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.