473,324 Members | 2,257 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,324 software developers and data experts.

arrays and strings misunderstanding...

Hello,

I wrote the tiny progam below just to understand arrays and strings
better.

I have 2 questions about arrays and strings in C.

1. Why is it that when you want to assign a string to an character array
that you must use the strcpy() function?

Why doesn't a assignment like gender = "male" not work for a character
array but for a pointer it works fine?

2. I declared a character array for 10 characters including the NULL
character, but as you see below I put more characters and it worked
fine. Can somebody explain me that please....

Thanks a lot in advance....

#include <stdio.h>
#include <string.h>

int main(void)
{
char *name;
char gender[10];

name = "broeisi";
strcpy(gender,"superb male");

printf("%s is a %s.\n",name, gender);

return 0;
}

This is the output of the program

broeisi@kitana Misc $ gcc arraystring.c -o arraystring
broeisi@kitana Misc $ ./arraystring
broeisi is a superb male.

I use gentoo linux with gcc version 3.4.4
Feb 16 '06 #1
6 1716
Broeisi wrote:
Hello,

I wrote the tiny progam below just to understand arrays and strings
better.

I have 2 questions about arrays and strings in C.

1. Why is it that when you want to assign a string to an character array
that you must use the strcpy() function?
You cannot assign to a character array, but you can assign to the array
elements. So if you want a char array to hold certain string, you need
to copy the chars.
Why doesn't a assignment like gender = "male" not work for a character
array but for a pointer it works fine?
An array is not a modifiable lvalue, so you cannot assign to it. A
pointer is a modifiable lvalue, that's why in the case of a pointer the
assignment works without problems. However if gender is a pointer the
assignment does not magically copy the string "male" to some
automagically allocated portion of memory. What it does make is storing
the address of the unnamed string literal "male" in the gender
variable.
2. I declared a character array for 10 characters including the NULL
character, but as you see below I put more characters and it worked
fine. Can somebody explain me that please....
You were unlucky. Stepping outside the boundaries of an array or
outside a dinamically allocated block of memory invokes undefined
behaviour, including seeming to work correctly. But the result could've
been anything, from crushing your computer to sending you a thousand
years into the past. (I'm tired of nasal demons... it's been a slow day
at work.)

HTH

Thanks a lot in advance....

#include <stdio.h>
#include <string.h>

int main(void)
{
char *name;
char gender[10];

name = "broeisi";
strcpy(gender,"superb male");

printf("%s is a %s.\n",name, gender);

return 0;
}

This is the output of the program

broeisi@kitana Misc $ gcc arraystring.c -o arraystring
broeisi@kitana Misc $ ./arraystring
broeisi is a superb male.

I use gentoo linux with gcc version 3.4.4


Feb 16 '06 #2
Antonio,

Thank you very much for your explanation.
It surely helped.

Have a nice and thanks again for your help.

Broeisi

Antonio Contreras wrote:
Broeisi wrote:
Hello,

I wrote the tiny progam below just to understand arrays and strings
better.

I have 2 questions about arrays and strings in C.

1. Why is it that when you want to assign a string to an character array
that you must use the strcpy() function?


You cannot assign to a character array, but you can assign to the array
elements. So if you want a char array to hold certain string, you need
to copy the chars.
Why doesn't a assignment like gender = "male" not work for a character
array but for a pointer it works fine?


An array is not a modifiable lvalue, so you cannot assign to it. A
pointer is a modifiable lvalue, that's why in the case of a pointer the
assignment works without problems. However if gender is a pointer the
assignment does not magically copy the string "male" to some
automagically allocated portion of memory. What it does make is storing
the address of the unnamed string literal "male" in the gender
variable.
2. I declared a character array for 10 characters including the NULL
character, but as you see below I put more characters and it worked
fine. Can somebody explain me that please....


You were unlucky. Stepping outside the boundaries of an array or
outside a dinamically allocated block of memory invokes undefined
behaviour, including seeming to work correctly. But the result could've
been anything, from crushing your computer to sending you a thousand
years into the past. (I'm tired of nasal demons... it's been a slow day
at work.)

HTH

Thanks a lot in advance....

#include <stdio.h>
#include <string.h>

int main(void)
{
char *name;
char gender[10];

name = "broeisi";
strcpy(gender,"superb male");

printf("%s is a %s.\n",name, gender);

return 0;
}

This is the output of the program

broeisi@kitana Misc $ gcc arraystring.c -o arraystring
broeisi@kitana Misc $ ./arraystring
broeisi is a superb male.

I use gentoo linux with gcc version 3.4.4


Feb 16 '06 #3
Broeisi wrote:
I wrote the tiny progam below just to understand arrays and strings
better.

I have 2 questions about arrays and strings in C.

1. Why is it that when you want to assign a string to an character array
that you must use the strcpy() function?

Why doesn't a assignment like gender = "male" not work for a character
array but for a pointer it works fine?
Because the original language designers simply didn't want to put that
in there. This stems from the fact that "strings" are not first-class
values in the C language. Characters are primitives, but strings are
not. Strings are basically "simulated" in the C language (and not very
well at that.)

The only sort of "primitive" support that the C language has for
strings is that inline strings (sequences of C source parsable chars
delimited by double quote characters) are interpreted in the form of
this simulation with its own implicit storage.
2. I declared a character array for 10 characters including the NULL
character, but as you see below I put more characters and it worked
fine. Can somebody explain me that please....

Thanks a lot in advance....

#include <stdio.h>
#include <string.h>

int main(void)
{
char *name;
char gender[10];

name = "broeisi";
This is not an array assignment, but a pointer assignment. The key
difference is that the storage for the string is declared by the value,
not the variable. So you cannot, for example, modify the value
"broeisi" by following this with a like like:

name[0] = 'd'; /* Ill defined, and will crash in some
environments. */

This is because the storage used comes from the value which is
considered unmutable (essentially, its implicitely const).
strcpy (gender, "superb male");


Here there are two strings. gender starts out uninitialized but this
is overwritten by the contents of the string "superb male". You have
an additional problem here because gender has only storage for 10
characters, but "superb male" is actually the following twelve
characters: { 's', 'u', 'p', 'e', 'r', 'b', ' ', 'm', 'a', 'l', 'e',
'\0' }; This is a buffer overflow, which you can learn all about here:

http://en.wikipedia.org/wiki/Buffer_Overflow

So long as the C language is just "simulating" strings rather than
providing a real primitive for them, there is an oppotunity for anyone
to write their own "simulation" for strings in the C language. "The
Better String Library" is one such example, and you can find the URL
for it at the bottom of this post. Using this library things are a
little more clear:

#include <stdio.h>
#include "bstrlib.h"

int main () {
struct tagbstring name = bsStatic ("broeisi");
bstring gender = blk2bstr (bsStaticBlkParms ("superb male"));

printf ("%s claims to be a %s.\n", name.data, bdatae (gender,
"??"));
bdestroy (gender);
return 0;
}

For a problem this small, the code isn't really shorter or simpler,
however the storage issue is somewhat clearer. Inline strings are
wrapped in bsStatic* macros which makes their storage clear. Also
issues like "buffer overflows" essentially disappear, since dynamic
storage container size issues are dealt with automatically in the
Better String Library (notice there is no value 10 anywhere in this
sample code), which is closer to what you find in other modern
languages.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Feb 16 '06 #4
Broeisi wrote:
I wrote the tiny progam below just to understand arrays and strings
better.

2. I declared a character array for 10 characters including the NULL
character, but as you see below I put more characters and it worked
fine. Can somebody explain me that please....
#include <stdio.h>
#include <string.h>

int main(void)
{
char *name;
char gender[10];
Reserve 10 bytes of memory for gender,
so the memory goes something like this

...........##########..........
aaaaaa<-GENDER->bbbbbb

Where "aaaaaa" and "bbbbbb" is memory reserved for something else or not
reserved at all (reserved for future use).

name = "broeisi";
strcpy(gender,"superb male");


Now the memory goes something like

...........superb male0........
aaaaaa<-GENDER->bbbbbb

So you've used memory space that doesn't belong to gender.
You might have overwritten something that was already there or that
final 'e0' may be overwritten by something else in your program removing
the terminating 0 from the string gender.

--
If you're posting through Google read <http://cfaj.freeshell.org/google>
Feb 16 '06 #5
On Thu, 16 Feb 2006 11:37:07 -0600, in comp.lang.c , Broeisi
<br*******@gmail.com> wrote:
1. Why is it that when you want to assign a string to an character array
that you must use the strcpy() function?
Because an array is an array, not a pointer. This is almost certainly
a FAQ by the way.
Why doesn't a assignment like gender = "male" not work for a character
array but for a pointer it works fine?
It depends what you mean by "work". In both cases, if you want to copy
the data, you must copy it, not assign a pointer to point to it.
2. I declared a character array for 10 characters including the NULL
character, but as you see below I put more characters and it worked
fine. Can somebody explain me that please....


You were unlucky. If your compiler and OS had been more robust, they
would have stopped your programme executing before it wrotte over
memory that did not belong to it.
By teh way, that was three questions, not two... :-)
Mark McIntyre
--
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-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 =----
Feb 16 '06 #6
Broeisi wrote:

<snip Broeisi question and my answer>
Antonio,

Thank you very much for your explanation.
It surely helped.

Have a nice and thanks again for your help.

Broeisi


You're wellcome. Glad I could help.

BTW, try to avoid top-posting. Other groups may have a more relaxed
attitude concerning netiquette, but c.l.c. has literally hundreds of
posts a day and top-posts makes reading them harder.

Feb 16 '06 #7

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

Similar topics

3
by: Java script Dude | last post by:
Some programmers prefer to stay with native level data structures such as string arrays instead of using Object based data structures such as ArrayList. From and efficiency point of view. Are...
5
by: harry | last post by:
I have 2 multi-dim arrays double subTotals = null; String rowTitles = null; I want to pass them to a function that initialises & populates them like so - loadData( rowTitles, subTotals);
4
by: agent349 | last post by:
First off, I know arrays can't be compared directly (ie: if (arrary1 == array2)). However, I've been trying to compare two arrays using pointers with no success. Basically, I want to take three...
34
by: Christopher Benson-Manica | last post by:
If an array is sparse, say something like var foo=; foo=4; foo='baz'; foo='moo'; is there a way to iterate through the entire array? --
5
by: Tarjei Romtveit | last post by:
I'm still a newbie into C++ programming, so I got a quite foolish string related question. Using: Dev-cpp 4.9.9.2 (I think Dev-Cpp uses a gcc compiler of some sort) If i declare a char...
10
by: Ian Todd | last post by:
Hi, I am trying to read in a list of data from a file. Each line has a string in its first column. This is what i want to read. I could start by saying char to read in 1000 lines to the array( i...
10
by: Pete | last post by:
Can someone please help, I'm trying to pass an array to a function, do some operation on that array, then return it for further use. The errors I am getting for the following code are, differences...
41
by: Rene Nyffenegger | last post by:
Hello everyone. I am not fluent in JavaScript, so I might overlook the obvious. But in all other programming languages that I know and that have associative arrays, or hashes, the elements in...
3
by: Mike Cain | last post by:
I have an odd situation I'm trying to understand..... I'm using MS VS 7.0 C++ with the MFC CBuffer class. If I do this: #define NUM_ELEMENTS 2 CBuffer<char, 512 x; CBuffer<char, 512 ...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.