[C] simple string question

A

Alan

hi all,

I want to define a constant length string, say 4
then in a function at some time, I want to set the string to a constant
value, say a
below is my code but it fails
what is the correct code?
many thx!


char string[4] = {0};

string = 'a '; /* <-- failed */
 
E

E. Robert Tisdale

Alan said:
I want to define a constant length string, say 4
then, in a function at some time,
I want to set the string to a constant value,
say a below is my code but it fails.
What is the correct code?

char string[4] = {0};

string = 'a '; /* <-- failed */

I'm going to assume that you really meant an array of characters.
In C, a *string* must be terminated by a nul character '\0'.

#include <string.h>

char array[4] = {0, 0, 0, 0};

memcpy(array, "a ", 4);
 
A

AirPete

Alan said:
hi all,

I want to define a constant length string, say 4
then in a function at some time, I want to set the string to a
constant value, say a
below is my code but it fails
what is the correct code?
many thx!


char string[4] = {0};

string = 'a '; /* <-- failed */

memcpy("abcd", string, sizeof(string));

- Pete
 
A

Alan

AirPete said:
Alan said:
hi all,

I want to define a constant length string, say 4
then in a function at some time, I want to set the string to a
constant value, say a
below is my code but it fails
what is the correct code?
many thx!


char string[4] = {0};

string = 'a '; /* <-- failed */

memcpy("abcd", string, sizeof(string));

sorry, but it doesn't work
when I run the program, the program crashes
 
L

Leor Zolman

Alan said:
hi all,

I want to define a constant length string, say 4
then in a function at some time, I want to set the string to a
constant value, say a
below is my code but it fails
what is the correct code?
many thx!


char string[4] = {0};

string = 'a '; /* <-- failed */

memcpy("abcd", string, sizeof(string));

- Pete

memcpy seems overkill for this, plus the usage is:
memcpy(destination, source, no_of_bytes);
On top of that, the memcpy call above would use up every existing
position in the char array, leaving no terminating NUL, which could
definitely lead to serious nastiness.

To initialize the string, an equivalent but in IMO clearer way to do
it would be:
char string[4] = ""; // still all nulled out

The point is to self-document the intention; you're representing an
empty "string" as opposed to "a bunch of numeric bytes". If you really
want to underscore the fact that the first byte is a "NUL" (the
character variety), you can instead say:
char string[4] = {'\0'}; // but please don't.

To change the value of the string, plain old strcpy works:

strcpy(string, "a");

If you're concerned about possibly overwriting the four available
bytes of the array (it wouldn't happen with the call above, but might
if you don't know for sure what the length of the string you're
copying from is), consider strncpy:

strncpy(string, some_source_ptr, 4);

However, this _still_ has the potential of leaving string without a
terminating null. You just have to be careful.

BTW, the 4's sprinkled throughout the code are bad style. In C, use a
#define to set that length up at the top somewhere...

Good luck,
-leor

Leor Zolman
BD Software
(e-mail address removed)
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
 
J

Josh Sebastian

hi all,

I want to define a constant length string, say 4
then in a function at some time, I want to set the string to a constant
value, say a
below is my code but it fails
what is the correct code?
many thx!


char string[4] = {0};

string = 'a '; /* <-- failed */

First off, double-quotes are used for string literals. Second off, you
can't assign to arrays. The best you can do is copy the characters from a
string into the array. strcpy() is used for that:

char string[4] = { 0 };
strcpy(string, "abc");

Note that the string "abc" is four characters long: 'a', 'b', 'c', and the
null terminator: '\0'.
 
C

Christopher Benson-Manica

In comp.lang.c Alan said:
char string[4] = {0};
string = 'a '; /* <-- failed */

As you've discovered, the first response to your post was completely
bogus. I'll try to do better (clc bogon catches appreciated):
char string[4] = {0};

string (a dubious name, but we'll go with it) as you've declared it is
an array of exactly four characters. You set each of these to zero
with your initialization. All is well.
string = 'a '; /* <-- failed */

This, as you know, is wrong. Strings cannot be assigned to in this
fashion in C. The way to accomplish the same thing is by using the
strcpy() function. Look it up in your friendly C book. Then, observe
that even if you succeeded with your assignment, you would still be
wrong. Your array is four characters, but your assignment needs
*five*, because strings in C must be terminated with '\0'.

Cuddle with your friendly C book, learn the ways of strings, and post
back when you're ready to try again. The fact that you aren't using
the correct string delimiter means you don't know enough about what you're
doing to be posting here.
 
M

Mac

Alan said:
I want to define a constant length string, say 4
then, in a function at some time,
I want to set the string to a constant value,
say a below is my code but it fails.
What is the correct code?

char string[4] = {0};

string = 'a '; /* <-- failed */

I'm going to assume that you really meant an array of characters.
In C, a *string* must be terminated by a nul character '\0'.

The OP's code does terminate the string. The assignment is obviously
wrong, but the initialization leaves the string terminated.
#include <string.h>

char array[4] = {0, 0, 0, 0};

This is a verbose way of doing the same thing as the OP.
memcpy(array, "a ", 4);

This leaves array as an array of chars, as you said. I just need to
emphasize to the OP that that is probably not a good idea.


--Mac
 
E

E. Robert Tisdale

Mac said:
E. Robert Tisdale said:
Alan said:
I want to define a constant length string, say 4
then, in a function at some time,
I want to set the string to a constant value,
say a below is my code but it fails.
What is the correct code?

char string[4] = {0};

string = 'a '; /* <-- failed */

I'm going to assume that you really meant an array of characters.
In C, a *string* must be terminated by a nul character '\0'.

The Alan's code does terminate the string.

More precisely, it leaves it *empty*.
The assignment is obviously wrong,
but the initialization leaves the string terminated.
#include <string.h>

char array[4] = {0, 0, 0, 0};

This is a verbose way of doing the same thing as the OP.
Yes.
memcpy(array, "a ", 4);

This leaves array as an array of chars, as you said.
I just need to emphasize to Alan that
that is probably not a good idea.

Agreed, if Alan really believes that
his string array is a character *string*.
His right-hand-side 'a ' contains four non-nul characters
so I can only assume that he believes string is really
just an array of four characters and *not* a string.
Actually, I think that Alan has *not* decided this point
and is still confused.
 
G

Gary

Christopher Benson-Manica said:
In comp.lang.c Alan said:
char string[4] = {0};
string = 'a '; /* <-- failed */
Cuddle with your friendly C book, learn the ways of strings, and post
back when you're ready to try again. The fact that you aren't using
the correct string delimiter means you don't know enough about what you're
doing to be posting here.

On the other hand, the fact that the OP didn't know enough about what he was
doing may be taken as precisely why he should be posting here.
See the word "learn" in the ng name? (Of course, what he may learn is that
not all responses are correct or helpful.)
 
A

Andrew Clark

Christopher Benson-Manica said:
In comp.lang.c Alan said:
char string[4] = {0};
string = 'a '; /* <-- failed */
Cuddle with your friendly C book, learn the ways of strings, and post
back when you're ready to try again. The fact that you aren't using
the correct string delimiter means you don't know enough about what
you're doing to be posting here.

On the other hand, the fact that the OP didn't know enough about what
he was doing may be taken as precisely why he should be posting here.
See the word "learn" in the ng name? (Of course, what he may learn is
that not all responses are correct or helpful.)

Yes, well

Notice, in Christopher's post, the line
^^^^^^^^^^^

As the OP was cross-posting, Christopher offered his reply from the NG
that does *not* contain 'learn' in the name.

Andrew
 
R

Richard Heathfield

Leor said:
To change the value of the string, plain old strcpy works:

strcpy(string, "a");

If you're concerned about possibly overwriting the four available
bytes of the array (it wouldn't happen with the call above, but might
if you don't know for sure what the length of the string you're
copying from is), consider strncpy:

strncpy(string, some_source_ptr, 4);

However, this _still_ has the potential of leaving string without a
terminating null. You just have to be careful.

It also has the potential to copy rather less of the data than was intended.
Copying too much data to a target is a bad idea, because it trashes memory,
and you are right to warn against this. But never forget that copying too
/little/ data from a source is /also/ a bad idea, because it generally
isn't what the program is meant to do!

The budding C programmer needs to learn, quite early on in life, that he or
she *must* ensure that the target is large enough for /all/ the data that
it needs to contain. Once you've ensured this, the choice between strcpy
and strncpy hinges entirely on your like, or dislike, for extra keystrokes.
 
G

Gary

Andrew Clark said:
Christopher Benson-Manica said:
char string[4] = {0};
string = 'a '; /* <-- failed */
Cuddle with your friendly C book, learn the ways of strings, and post
back when you're ready to try again. The fact that you aren't using
the correct string delimiter means you don't know enough about what
you're doing to be posting here.

On the other hand, the fact that the OP didn't know enough about what
he was doing may be taken as precisely why he should be posting here.
See the word "learn" in the ng name? (Of course, what he may learn is
that not all responses are correct or helpful.)

Yes, well

Notice, in Christopher's post, the line
^^^^^^^^^^^

As the OP was cross-posting, Christopher offered his reply from the NG
that does *not* contain 'learn' in the name.

You are absolutely right! I don't read the comp.lang.c ng because there is
nothing to learn there.
 
R

Richard Heathfield

Gary said:
I don't read the comp.lang.c ng because there is
nothing to learn there.

That's odd. I thought I was a C expert until I started using the comp.lang.c
newsgroup. Its regular contributors taught me an immense amount about the
language.

If you wish to learn about C, perhaps you should look at comp.lang.c a
little harder.
 
A

AirPete

E. Robert Tisdale said:
You got the source and destination arrays confused.

Oops, thanks for pointing it out!
I even looked at the documentation twice :)

- Pete
 
A

AirPete

Christopher said:
In comp.lang.c Alan said:
char string[4] = {0};
string = 'a '; /* <-- failed */

As you've discovered, the first response to your post was completely
bogus. I'll try to do better (clc bogon catches appreciated):

Except for my accidental argument misordering, what was wrong/incorrect?
Alan (OP) asked how to move a *constant* length string, which memcpy does
quite nicely.
There is plenty of uses for constant length strings; sometimes they're more
suitable for the task.

[snip]
 
A

AirPete

Alan wrote:
[snip]
sorry, but it doesn't work
when I run the program, the program crashes

Sorry, I got the arguments misordered, it should be:
memcpy(string, "abcd", sizeof(string));
 
C

Christopher Benson-Manica

In comp.lang.c AirPete said:
Except for my accidental argument misordering, what was wrong/incorrect?

As others pointed out, you missed a '\0' character at the end of the
string.
Alan (OP) asked how to move a *constant* length string, which memcpy does
quite nicely.

strcpy() does it even more nicely, assuming the destination is
sufficiently large. Among other things, it prevents the above mistake
entirely.
 
L

Leor Zolman

It also has the potential to copy rather less of the data than was intended.
Copying too much data to a target is a bad idea, because it trashes memory,
and you are right to warn against this. But never forget that copying too
/little/ data from a source is /also/ a bad idea, because it generally
isn't what the program is meant to do!

But in the case of copying into a "string" (char array) buffer, it
seems to me that copying "too little" is exactly what you'd _want_ it
to do. As the subject of the post is "simple string question", I don't
see the point of reading extra requirements into the problem; I didn't
see any indication in the OP's (admittedly sparse) code that "string"
was to be used in any way other than as a nul-terminating string, and
in that context I'd vote for strcpy/strncpy being the best choice.
The budding C programmer needs to learn, quite early on in life, that he or
she *must* ensure that the target is large enough for /all/ the data that
it needs to contain. Once you've ensured this, the choice between strcpy
and strncpy hinges entirely on your like, or dislike, for extra keystrokes.

IMO, a budding C programmer also needs to understand the concept of
nul-terminated strings and all of the implication of using them,
including fundamental efficiency issues that are in the spirit of C...
I'd place the order of importance of all the things we've discussed
as:
1. not overflowing buffers
2. doing things efficiently
3. filling in dead space (?)
Cheers,
-leor


Leor Zolman
BD Software
(e-mail address removed)
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,191
Latest member
BuyKetoBeez

Latest Threads

Top