473,383 Members | 1,725 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,383 software developers and data experts.

Char pointer - How to give value?

Hi,

I have just started learning C and am working on pointers but am
having difficulty with the following:

If i have a struct, that includes a pointer to char (in my case, i've
named it filename), and in the main code, I want to use that pointer
to create a memory location and assign a character string.

I have gotten the following in the main code (structPtr is a pointer
to they type of struct i have created):

structPtr->filename = malloc(10 * sizeof(char));

How do I give a value, lets stay string value of "cust.txt" to this
field?

Will appreciate any help,

Thanks,

Alij

Mar 19 '07 #1
10 5309
On Mar 19, 6:49 pm, "alij" <aliasger.jaf...@gmail.comwrote:
Hi,

I have just started learning C and am working on pointers but am
having difficulty with the following:

If i have a struct, that includes a pointer to char (in my case, i've
named it filename), and in the main code, I want to use that pointer
to create a memory location and assign a character string.

I have gotten the following in the main code (structPtr is a pointer
to they type of struct i have created):

structPtr->filename = malloc(10 * sizeof(char));

How do I give a value, lets stay string value of "cust.txt" to this
field?
strcpy(structPtr->filename,"cust.txt");

By the way, sizeof(char) is always 1, so malloc(10) will do.
Will appreciate any help,

Thanks,

Alij

Mar 19 '07 #2
On Mar 19, 1:58 pm, Francine.Ne...@googlemail.com wrote:
On Mar 19, 6:49 pm, "alij" <aliasger.jaf...@gmail.comwrote:
Hi,
I have just started learning C and am working on pointers but am
having difficulty with the following:
If i have a struct, that includes a pointer to char (in my case, i've
named it filename), and in the main code, I want to use that pointer
to create a memory location and assign a character string.
I have gotten the following in the main code (structPtr is a pointer
to they type of struct i have created):
structPtr->filename = malloc(10 * sizeof(char));
How do I give a value, lets stay string value of "cust.txt" to this
field?

strcpy(structPtr->filename,"cust.txt");

By the way, sizeof(char) is always 1, so malloc(10) will do.
Will appreciate any help,
Thanks,
Alij
Thank you for your help!!

Mar 19 '07 #3
alij wrote:
Hi,

I have just started learning C and am working on pointers but am
having difficulty with the following:

If i have a struct, that includes a pointer to char (in my case, i've
named it filename), and in the main code, I want to use that pointer
to create a memory location and assign a character string.

I have gotten the following in the main code (structPtr is a pointer
to they type of struct i have created):

structPtr->filename = malloc(10 * sizeof(char));
^^^^^^^^^^^^^^
sizeof(char) is 1 by definition. The above is typing practice to no end.
>
How do I give a value, lets stay string value of "cust.txt" to this
field?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define FIELDSIZE 10
#define FILENAME "cust.txt"

struct foo
{
char *filename;
};

int main(void)
{
struct foo thething, *structPtr = &thething;

if (!(structPtr->filename = malloc(FIELDSIZE))) {
printf("malloc failed. I quit!\n");
exit(EXIT_FAILURE);
}
if (strlen(FILENAME) >= FIELDSIZE) {
printf("\"" FILENAME "\" is too long. I quit!\n");
free(structPtr->filename);
exit(EXIT_FAILURE);
}
strcpy(structPtr->filename, FILENAME);
printf("structPtr->filename is \"%s\"\n"
" and thething.filename is \"%s\"\n",
structPtr->filename, thething.filename);
free(structPtr->filename);
return 0;
}
structPtr->filename is "cust.txt"
and thething.filename is "cust.txt"
Mar 19 '07 #4
alij wrote:
I have gotten the following in the main code (structPtr is a pointer
to they type of struct i have created):

structPtr->filename = malloc(10 * sizeof(char));

How do I give a value, lets stay string value of "cust.txt" to this
field?
You need to copy the data from one place in memory (your "cust.txt" in
the code also ends up somewhere in memory) to another; the most normal
way is with the standard library function strcpy(), as in:

strcpy(structPtr->filename, "cust.txt");

But watch out that the string you are copying is not longer than the
place you have allocated (with room for the null-character that
terminates the string)! Otherwise you have a "buffer overflow" and will
destroy internal data structures and your program will most probably crash.

A function that is useful to avoid these problems is strncpy(), which
takes the maximal string length as extra argument.

Or you first find out how long the content is, and then allocate the
buffer space for it; this avoids artificial limits in the code. Like this:

/* imagine a more interesting way to get the content, it's an example */
const char* content = "cust.txt";
int n = strlen(content);
/* allocate memory for the string, plus 1 byte for termination */
structPtr->filename = malloc(n+1);
/* make sure we have the memory */
if (structPtr->filename == NULL)
exit(1); /* or some other way to give up */
/* copy the content */
strcpy(structPtr->filename, content);

Have fun,

Tobias
Mar 19 '07 #5
Tobias Rischer wrote:
alij wrote:
I have gotten the following in the main code (structPtr is a pointer
to they type of struct i have created):

structPtr->filename = malloc(10 * sizeof(char));

How do I give a value, lets stay string value of "cust.txt" to this
field?

You need to copy the data from one place in memory (your "cust.txt" in
the code also ends up somewhere in memory) to another; the most normal
way is with the standard library function strcpy(), as in:

strcpy(structPtr->filename, "cust.txt");

But watch out that the string you are copying is not longer than the
place you have allocated (with room for the null-character that
terminates the string)! Otherwise you have a "buffer overflow" and will
destroy internal data structures and your program will most probably crash.

A function that is useful to avoid these problems is strncpy(), which
takes the maximal string length as extra argument.
the semantics of strncpy() are non-intuitive (it's broken). So
generally
*don't* use strncpy.

/* what is wrong with this? */
char sbuff[4];
strncpy(sbuff, "bomb", 4);
printf ("%s\n", buff);

/* how many characters are written to bbuff? */
char *bbuff [1000000];
strncpy(bbuff, "bomb", 1000000);

<snip>
--
Nick Keighley

Mar 20 '07 #6

Nick Keighley wrote:
Tobias Rischer wrote:
alij wrote:
I have gotten the following in the main code (structPtr is a pointer
to they type of struct i have created):
>
structPtr->filename = malloc(10 * sizeof(char));
>
How do I give a value, lets stay string value of "cust.txt" to this
field?
You need to copy the data from one place in memory (your "cust.txt" in
the code also ends up somewhere in memory) to another; the most normal
way is with the standard library function strcpy(), as in:

strcpy(structPtr->filename, "cust.txt");

But watch out that the string you are copying is not longer than the
place you have allocated (with room for the null-character that
terminates the string)! Otherwise you have a "buffer overflow" and will
destroy internal data structures and your program will most probably crash.

A function that is useful to avoid these problems is strncpy(), which
takes the maximal string length as extra argument.

the semantics of strncpy() are non-intuitive (it's broken). So
generally
*don't* use strncpy.

/* what is wrong with this? */
char sbuff[4];
strncpy(sbuff, "bomb", 4);
printf ("%s\n", buff);

/* how many characters are written to bbuff? */
char *bbuff [1000000];
char bbuff [1000000];

how did that happen?
strncpy(bbuff, "bomb", 1000000);

<snip>
--
Nick Keighley
Mar 20 '07 #7
On Mar 20, 7:17 am, "Nick Keighley" <nick_keighley_nos...@hotmail.com>
wrote:
Tobias Rischer wrote:
alij wrote:
I have gotten the following in the main code (structPtr is a pointer
to they type of struct i have created):
structPtr->filename = malloc(10 * sizeof(char));
How do I give a value, lets stay string value of "cust.txt" to this
field?
You need to copy the data from one place in memory (your "cust.txt" in
the code also ends up somewhere in memory) to another; the most normal
way is with the standard library function strcpy(), as in:
strcpy(structPtr->filename, "cust.txt");
But watch out that the string you are copying is not longer than the
place you have allocated (with room for the null-character that
terminates the string)! Otherwise you have a "buffer overflow" and will
destroy internal data structures and your program will most probably crash.
A function that is useful to avoid these problems is strncpy(), which
takes the maximal string length as extra argument.

the semantics of strncpy() are non-intuitive (it's broken). So
generally
*don't* use strncpy.

/* what is wrong with this? */
char sbuff[4];
strncpy(sbuff, "bomb", 4);
printf ("%s\n", buff);

/* how many characters are written to bbuff? */
char *bbuff [1000000];
strncpy(bbuff, "bomb", 1000000);

<snip>

--
Nick Keighley- Hide quoted text -

- Show quoted text -
neither of these seem to show strncpy() as broken. This is C
programming after all. Both examples are basically user error. Would
you also say a 1970's car is broken because it does not have ABS?

Ed

Mar 26 '07 #8
On 26 Mar, 16:57, "Ed Prochak" <edproc...@gmail.comwrote:
On Mar 20, 7:17 am, "Nick Keighley" <nick_keighley_nos...@hotmail.com>
wrote:
<snip>
Tobias Rischer wrote:
the semantics of strncpy() are non-intuitive (it's broken). So
generally
*don't* use strncpy.
<snip>
>
neither of these seem to show strncpy() as broken. This is C
programming after all. Both examples are basically user error. Would
you also say a 1970's car is broken because it does not have ABS?
I don't think he meant it literally, just that's it harder to use than
it should be.

You use the example of a 1970's car without ABS. I completely see
your point.

However, I think a better analogy is the good old vending machine
which labels BOTH rows and columns with numbers. People using the
machine who don't stop to think sometimes end up putting the price in
instead of the product identifier. (Maybe they're busy in their head
trying to figure out why strncpy doesn't do what they think it does!)

Now, the vending machine isn't 'broken'. But it's a silly design and
no one uses it. Pretty much all of them label one axis with a number
and the other with a letter. Thus, it's impossible to enter 59 pence
(or cents or whatever) and you generally end up with what you wanted.
Instead of something that's technically correct, but just likely to
piss you off.

I don't think strncpy is as bad as all that, but it's certainly not
'good' from the point of view of ease of use. It would not have been
difficult or performance-costly to have designed a sensible strncpy.
Oh well, eh?

Doug

Mar 26 '07 #9
On Mar 20, 12:17 pm, "Nick Keighley"
<nick_keighley_nos...@hotmail.comwrote:
the semantics of strncpy() are non-intuitive (it's broken). So
generally
*don't* use strncpy.

/* what is wrong with this? */
char sbuff[4];
strncpy(sbuff, "bomb", 4);
printf ("%s\n", buff);

There's nothing inherently wrong with that. It copies
4 characters into sbuff. It doesn't include a null,
so sbuff doesn't contain a proper string, but I don't
find that un-intuitive at all, quite the opposite.
Perhaps you think it would be better if the above
code made sbuff's first 4 entries be: 'b', 'o', 'm', '\0',
....but it doesn't.

>
/* how many characters are written to bbuff? */
char *bbuff [1000000];
strncpy(bbuff, "bomb", 1000000);
(ignoring the syntax error)...this copies 1000000
characters into bbuff. I don't see how this
is non-intuitive.

In each case, the number of characters written
is the 3rd argument, and those characters
match the values given in the 2nd argument.
It seems to me that mangling the semantics
to ensure that the result is a proper string
would be non-intuitive. What do you propose
would be better?

--
Bill Pursell

Mar 26 '07 #10
Bill Pursell wrote:
On Mar 20, 12:17 pm, "Nick Keighley"
<nick_keighley_nos...@hotmail.comwrote:
the semantics of strncpy() are non-intuitive (it's broken). So
generally *don't* use strncpy.

/* what is wrong with this? */
char sbuff[4];
strncpy(sbuff, "bomb", 4);
printf ("%s\n", buff);


There's nothing inherently wrong with that.
true. It is well defined what it does.
It copies
4 characters into sbuff. It doesn't include a null,
so sbuff doesn't contain a proper string, but I don't
find that un-intuitive at all, quite the opposite.
Perhaps you think it would be better if the above
code made sbuff's first 4 entries be: 'b', 'o', 'm', '\0',
...but it doesn't.
I would prefer that. Perhaps my objection is its name.
Since it has "str" in its name and modifies a string
I think it would be reasonable to expect the resulting
char* to also be a string.
/* how many characters are written to bbuff? */
char bbuff [1000000];
strncpy(bbuff, "bomb", 1000000);

(ignoring the syntax error)...
I've fixed it (I hope!)
this copies 1000000
characters into bbuff. I don't see how this
is non-intuitive.

In each case, the number of characters written
is the 3rd argument, and those characters
match the values given in the 2nd argument.
It seems to me that mangling the semantics
to ensure that the result is a proper string
would be non-intuitive. What do you propose
would be better?
ones man's mangling is another man's intuitive semantics...

I'd prefer the result of the operation to always be a string.
No more characters copied than necessary to create a string
(like strcpy()).
And argument 3 to be the maximum number of chars written.

In other words I want a strcpy() with a limit on the number of
characters written.

Example one would write 4 characters and produce a string
of length 3.

Example two would write 5 characters and produce a string
of length 4.

I have never found a use for strncpy(). I have used a function
with the semantics above and found it useful.

I have seen strncpy misused many times (more often than not).
People often express surprise when I point out the actual
semantics of strncpy (perhaps I know too many people that
don't RTFM).
--
Nick Keighley

Mar 28 '07 #11

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

Similar topics

19
by: Espen Ruud Schultz | last post by:
Lets say I have a char pointer and an std::string. Is it possible to get a pointer to the std::string's "content" so that the char pointer can point to the same text? And vice versa; can I give...
22
by: bvb | last post by:
Hi, while declaring/defining pointer to int/char, What is doing the compiler exactly . i'm able to get output(String) for all pointer to char definition(without line # 8&14). But when i include...
5
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...
33
by: baumann.Pan | last post by:
hi all, i want to get the address of buf, which defined as char buf = "abcde"; so can call strsep(address of buf, pointer to token);
13
by: chellappa | last post by:
hi , please explain me , char pointer , char Array, char ,string... i have some many confussion about this... please clarify to me.. i need some example about this program by chellappa.ns
22
by: Jack | last post by:
The following code can be compiled. But When I run it, it causes "Segmentation fault". int main(){ char **c1; *c1 = "HOW"; // LINE1 ++(*c1); *c1 = "ARE";
18
by: planetzoom | last post by:
Given the following code: #include <stdio.h> int main(void) { char array = "What is your favorite car?"; void *vp = &array; printf("%s\n", vp);
30
by: Yevgen Muntyan | last post by:
Hey, Why is it legal to do union U {unsigned char u; int a;}; union U u; u.a = 1; u.u; I tried to find it in the standard, but I only found that
43
by: emyl | last post by:
Hi all, here's an elementary question. Assume I have declared two variables, char *a, **b; I can then give a value to a like a="hello world";
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...
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...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.