473,785 Members | 2,209 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

arrays and strings misunderstandin g...

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 1760
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 (bsStaticBlkPar ms ("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

...........supe rb 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*******@gmai l.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
4853
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 string arrays the most efficient way of dealing with static tabular data such as query returns? or is it more efficient to use a Recordset type data structure using say ArrayList with a Record objects? (Pardon my JDBC ignorance)
5
12624
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
10538
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 sets of character strings from the user. Then I want to run through each element and compare the two strings. If they match I print they match... I'm having a bit of trouble with the actual loop through each array using the pointers and comparing...
34
4239
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
11409
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 string like this: char szString = "Hello";
10
9041
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 think!!). But I want to use malloc. Each string is at most 50 characters long, and there may be zero to thousands of lines. How do I actually start the array? I have seen char **array etc. At first I tried char *array but I think that gives 50...
10
3172
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 in levels of indirection, so I feel it must have something to do with the way I am representing the array in the call and the return. Below I have commented the problem parts. Thanks in advance for any help offered. Pete
41
4980
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 the hash are alphabetically sorted if the key happens to be alpha numeric. Which I believe makes sense because it allows for fast lookup of a key.
3
1725
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 y; So as you can see I have two variables which will hold strings, each of
0
9646
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
9484
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
10350
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
10157
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
9957
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
7505
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
5386
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...
1
4055
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
2
3658
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.