473,669 Members | 2,504 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

char* and char[]?

179 New Member
Just wondering if someone can clear things up for me a little. I'm fairly new to C/C++ and just getting in a bit of a tangle with pointers.

My problem is I have a vector of a defined structure, which needs to store some characters. When I try and print out these characters later, it appears to be uninitialised. I believe the problem is because I'm using a char*, who's memory contents then just gets discarded later on, and hence I can't get the characters anymore.

e.g.

Expand|Select|Wrap|Line Numbers
  1. typedef struct _info{
  2.     char* label;
  3. } Info;
a little later on some parsing takes place...

Expand|Select|Wrap|Line Numbers
  1. char *value;
  2.  
  3. for (....)
  4. {
  5.   char *label;
  6.   Info info;
  7.   label = value;
  8.   info.label = label;
  9.  
  10.   // info gets added to a vector
  11. }
  12.  
When I come to print info later I get ▌▌▌▌▌▌▌▌▌▌

Is my understanding of this correct? If so, then I guess that label within the Info structure needs to be a char[]. Is there a simple way to then copy the 'value' within the for loop into this char array as my attempts have just led to compiler errors... ?

Thanks very much
Feb 7 '08 #1
6 2075
IanWright
179 New Member
I'm going to reply to my own question for the benefit of anyone else...

I think explaining the problem is right, and the useful little way to do this is to use strcpy...

Expand|Select|Wrap|Line Numbers
  1. char dest[50];
  2. char* pointer = "hello world";
  3.  
  4. strcpy(dest, pointer);
  5.  
pointer can now be played around with freely without changing the value in dest.
Feb 7 '08 #2
weaknessforcats
9,208 Recognized Expert Moderator Expert
A char* is a pointer to a single char.

A char[] is also a pointer to a char but you have to specify the char(s) or it won't compile:
Expand|Select|Wrap|Line Numbers
  1. char arr[] ="ABC";  /* OK. arr is an array of 4 char */
  2. char arr1[] = {'A', 'B', 'C'};   /* OK. arr1 is an array of 3 char */
  3. char arr2[];            /* ERROR: No char(s) specified.
  4.  
Read this:
First, there are only one-dimensional arrays in C or C++. The number of elements in put between brackets:
Expand|Select|Wrap|Line Numbers
  1. int array[5];
  2.  
That is an array of 5 elements each of which is an int.

Expand|Select|Wrap|Line Numbers
  1. int array[];
  2.  
won't compile. You need to declare the number of elements.

Second, this array:
Expand|Select|Wrap|Line Numbers
  1. int array[5][10];
  2.  
is still an array of 5 elements. Each element is an array of 10 int.

Expand|Select|Wrap|Line Numbers
  1. int array[5][10][15];
  2.  
is still an array of 5 elements. Each element is an array of 10 elements where each element is an array of 15 int.


Expand|Select|Wrap|Line Numbers
  1. int array[][10];
  2.  
won't compile. You need to declare the number of elements.

Third, the name of an array is the address of element 0
Expand|Select|Wrap|Line Numbers
  1. int array[5];
  2.  
Here array is the address of array[0]. Since array[0] is an int, array is the address of an int. You can assign the name array to an int*.

Expand|Select|Wrap|Line Numbers
  1. int array[5][10];
  2.  
Here array is the address of array[0]. Since array[0] is an array of 10 int, array is the address of an array of 10 int. You can assign the name array to a pointer to an array of 10 int:
Expand|Select|Wrap|Line Numbers
  1. int array[5][10];
  2.  
  3. int (*ptr)[10] = array;
  4.  
Fourth, when the number of elements is not known at compile time, you create the array dynamically:

Expand|Select|Wrap|Line Numbers
  1. int* array = new int[value];
  2. int (*ptr)[10] = new int[value][10];
  3. int (*ptr)[10][15] = new int[value][10][15];
  4.  
In each case value is the number of elements. Any other brackets only describe the elements.

Using an int** for an array of arrays is incorrect and produces wrong answers using pointer arithmetic. The compiler knows this so it won't compile this code:

Expand|Select|Wrap|Line Numbers
  1. int** ptr = new int[value][10];    //ERROR
  2.  
new returns the address of an array of 10 int and that isn't the same as an int**.

Likewise:
Expand|Select|Wrap|Line Numbers
  1. int*** ptr = new int[value][10][15];    //ERROR
  2.  
new returns the address of an array of 10 elements where each element is an array of 15 int and that isn't the same as an int***.

With the above in mind this array:
Expand|Select|Wrap|Line Numbers
  1. int array[10] = {0,1,2,3,4,5,6,7,8,9};
  2.  
has a memory layout of

0 1 2 3 4 5 6 7 8 9

Wheras this array:
Expand|Select|Wrap|Line Numbers
  1. int array[5][2] = {0,1,2,3,4,5,6,7,8,9};
  2.  
has a memory layout of

0 1 2 3 4 5 6 7 8 9

Kinda the same, right?

So if your disc file contains

0 1 2 3 4 5 6 7 8 9

Does it make a difference wheher you read into a one-dimensional array or a two-dimensional array? No.

Therefore, when you do your read use the address of array[0][0] and read as though you have a
one-dimensional array and the values will be in the correct locations.
Feb 7 '08 #3
Rajesh V
15 New Member
In your post, you have said that

Expand|Select|Wrap|Line Numbers
  1. int array[][10]; 
  2.  
won't compile because we need to declare the number of elements.

But, if i do like this,

Expand|Select|Wrap|Line Numbers
  1. int array[10][];
  2.  
The compiler gives the error - declaration of ‘a’ as multidimensiona l array must have bounds for all dimensions except the first

Also, when i do like this,

int array[][10] = { { 0 } };

It gets compiled successfully.

Can you please explain what's happening?
Feb 7 '08 #4
Andr3w
42 New Member
Well, for the last used declariation with the zero you initialize the variable to be like this:

Expand|Select|Wrap|Line Numbers
  1. int index[1][10] = { 0 };
  2.  
Also you don't need a "duo" of curly brackets for that like you used... Anyway I think that weaknessforcats meant the following use:

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. int Size(int index[][3]);
  4. int main(int argc, char **argv)
  5. {
  6. // the first dimention (currently has a value of 1 can be any value
  7. // the function will accept it, so it would be valid to write
  8. // index[10][3]. the function would be ok with it!
  9.     int index[1][3];
  10.  
  11.     Size(index);
  12.     return 0;
  13. }
  14.  
  15. int Size(int index[][3])
  16. {
  17.     return;
  18. }
  19.  
I hope this example helped you understand what's going on! Should you have any questions post!
Feb 7 '08 #5
weaknessforcats
9,208 Recognized Expert Moderator Expert
In your post, you have said that


Code: ( text )
int array[][10];


won't compile because we need to declare the number of elements.

But, if i do like this,


Code: ( text )
int array[10][];


The compiler gives the error - declaration of ‘a’ as multidimensiona l array must have bounds for all dimensions except the first
Yep.
Expand|Select|Wrap|Line Numbers
  1. int array[10][];
  2.  
can't compile becuse you failed to specify the size of the elements.
Feb 8 '08 #6
weaknessforcats
9,208 Recognized Expert Moderator Expert
int array[][10] = { { 0 } };

It gets compiled successfully.

Can you please explain what's happening?
You are using initialization syntax. This is the same as:
Expand|Select|Wrap|Line Numbers
  1. int array[1][10] = { { 0 } };
  2.  
Rememvber:
Expand|Select|Wrap|Line Numbers
  1. int arr[] = {1,2,3,4,5};
  2.  
is the same as:
Expand|Select|Wrap|Line Numbers
  1. int arr[5] = {1,2,3,4,5};
  2.  
Feb 8 '08 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

9
2202
by: Christopher Benson-Manica | last post by:
I need a smart char * class, that acts like a char * in all cases, but lets you do some std::string-type stuff with it. (Please don't say to use std::string - it's not an option...). This is my attempt at it, but it seems to be lacking... I'm aware that strdup() is nonstandard (and a bad idea for C++ code) - please just bear with me: /* Assume relevant headers are included */ class char_ptr {
5
9735
by: Alex Vinokur | last post by:
"Richard Bos" <rlb@hoekstra-uitgeverij.nl> wrote in message news:4180f756.197032434@news.individual.net... to news:comp.lang.c > ben19777@hotmail.com (Ben) wrote: > > 2) Structure casted into an array of char > > typedef struct { > > char name; > > int age; > > int id; > > } person; > >
5
2532
by: Sona | last post by:
I understand the problem I'm having but am not sure how to fix it. My code passes two char* to a function which reads in some strings from a file and copies the contents into the two char*s. Now when my function returns, the values stored in the char* are some garbage values (perhaps because I didn't allocate any memory for them).. but even if I allocate memory in the function, on the return of this function I see garbage.. here is my...
2
3406
by: Peter Nilsson | last post by:
In a post regarding toupper(), Richard Heathfield once asked me to think about what the conversion of a char to unsigned char would mean, and whether it was sensible to actually do so. And pete has raised a doubt in my mind on the same issue. Either through ignorance or incompetence, I've been unable to resolve some issues. 6.4.4.4p6 states...
5
3963
by: jab3 | last post by:
(again :)) Hello everyone. I'll ask this even at risk of being accused of not researching adequately. My question (before longer reasoning) is: How does declaring (or defining, whatever) a variable **var make it an array of pointers? I realize that 'char **var' is a pointer to a pointer of type char (I hope). And I realize that with var, var is actually a memory address (or at
12
10079
by: GRoll35 | last post by:
I get 4 of those errors. in the same spot. I'll show my parent class, child class, and my driver. All that is suppose to happen is the user enters data and it uses parent/child class to display it. here is the 4 errors. c:\C++\Ch15\Employee.h(29): error C2440: '=' : cannot convert from 'char ' to 'char '
18
4047
by: Pedro Pinto | last post by:
Hi there once more........ Instead of showing all the code my problem is simple. I've tried to create this function: char temp(char *string){ alterString(string); return string;
4
3219
by: Paul Brettschneider | last post by:
Hello all, consider the following code: typedef char T; class test { T *data; public: void f(T, T, T); void f2(T, T, T);
16
6784
by: s0suk3 | last post by:
This code #include <stdio.h> int main(void) { int hello = {'h', 'e', 'l', 'l', 'o'}; char *p = (void *) hello; for (size_t i = 0; i < sizeof(hello); ++i) {
29
9964
by: Kenzogio | last post by:
Hi, I have a struct "allmsg" and him member : unsigned char card_number; //16 allmsg.card_number
0
8383
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
8895
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
8809
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
8658
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
7407
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...
0
5682
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
4206
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
4386
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2032
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.