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 6 1762
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
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
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/
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>
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 =----
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. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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)
|
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);
|
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...
|
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?
--
|
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";
| |
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...
|
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
|
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.
|
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
|
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...
|
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...
| |
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...
|
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...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |