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

reassigning value of a pointer

Hi all,

In the following code I am trying to change the contents of a string:

int main()
{
char *string="testing";
rename(string);

return 0;
}

void rename(char *s)
{
printf("Character 1: %c\n",*s);
*s='a';
printf("Character 1 now: %c\n",*c);
}

Anyway, I am sure this is possible but for some reason I'm getting
segmentation faults at line *s='a'; when I attempt to change the value
in which *s is currently pointing to, being the first character in the
string.

Any ideas?

Thanks in advance,

Ben.

Nov 15 '05 #1
20 5393
In article <11**********************@g14g2000cwa.googlegroups .com>,
<bh******@dodo.com.au> wrote:
In the following code I am trying to change the contents of a string: int main()
{
char *string="testing";


The standard allows string literals to be stored in read-only memory.
An assignment of a string literal to a pointer sets the pointer value
to the address of that {possibly read-only} memory.

In particular, char *string="testing"; usually does not allocate some
memory somewhere and copy the string into it at runtime. That's
one of the possible behaviours, but it isn't the only possible
behaviour.

Another thing to note is that it is allowed for the compiler
to merge all string literals -- so for example if you also had

char *anotherstring="testing";

then anotherstring could end up as the same pointer value as
your string variable. Furthermore, if you had

char *thirdstring="just testing";

then string and anotherstring could end up pointing at the terminal
"testing" substring of the "just testing".

If you need a modifiable string, allocate the memory (somehow) and
copy the appropriate contents into it.
--
"It is important to remember that when it comes to law, computers
never make copies, only human beings make copies. Computers are given
commands, not permission. Only people can be given permission."
-- Brad Templeton
Nov 15 '05 #2
Thanks for that information Walter. I managed to get it working, by
allocating the memory then using strcpy to load the string.

Regards,

Ben.

Nov 15 '05 #3
bh******@dodo.com.au wrote:
Hi all,

In the following code I am trying to change the contents of a string:
Then don't use string literals.

int main()
{
char *string="testing";


If you want to change the string, don't make 'string' point to a literal
constant; use an array:
char string[] = "testing";

Always check the FAQ before posting. In this case, you might have found
<http://www.eskimo.com/~scs/C-faq/q1.32.html> useful.
Nov 15 '05 #4
in the above program what is "c", not declared in the program, first u
declare that and assign a value and then print it ok. i think that
there is no problem in the line *s='a';
so try it and send me the result.

Nov 15 '05 #5
Martin Ambuhl wrote:
Then don't use string literals. If you want to change the string,
don't make 'string' point to a literal constant;
There is no such thing as a "literal constant" in C.
char string[] = "testing";


You just used a string literal to initialize an array.

--
pete
Nov 15 '05 #6
bh******@dodo.com.au wrote:
int main()
{
char *string="testing";
rename(string);


Your immediate problem is as others have explained it. However, you have
another bug: rename() is already a Standard function, and you cannot
redefine it, let alone redefine it with an incompatible declaration.

Richard
Nov 15 '05 #7
It becomes a standard function iff (if and only if) you include
<stdio.h>. Although dubbed as *Standard* Input Ouput - not really a
standard. Any programmer could redefine functions already defined in
*Standard* headers. Other than that, what the original author intended
to do clearly shouldn't be named as rename(..); rather,
change_sptr(...); Or something simliar.

Nov 15 '05 #8
David G. Hong wrote:

It becomes a standard function iff (if and only if) you include
<stdio.h>.


How do you figure that?

N869
7.1.3 Reserved identifiers
[#1]
-- All identifiers with external linkage in any of the
following subclauses (including the future library
directions) are always reserved for use as identifiers
with external linkage.

--
pete
Nov 15 '05 #9
David G. Hong wrote:

Provide context. This is possible and instructions were posted only
yesterday, so had you read the group before posting (you should always
read a few days posts before your first post to a group) you would have
know to do this and *how* to do it. It's something like pressing the
"options" button and using the reply button that provides.
It becomes a standard function iff (if and only if) you include
<stdio.h>. Although dubbed as *Standard* Input Ouput - not really a
standard. Any programmer could redefine functions already defined in
*Standard* headers.
Wrong. The standard does not allow you to redefine *any* of the standard
functions whether you include the relevant header or not. *Some*
implementations allow you to do this and define the behaviour, but it is
not portable.
Other than that, what the original author intended
to do clearly shouldn't be named as rename(..); rather,
change_sptr(...); Or something simliar.


Well, since you've not provided any context it is hard to tell what a
sensible name would be.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #10
On Wed, 28 Sep 2005 06:34:39 +0000, pete wrote:
Martin Ambuhl wrote:
Then don't use string literals.

If you want to change the string,
don't make 'string' point to a literal constant;


There is no such thing as a "literal constant" in C.


It is a resonable description of a string literal object.
char string[] = "testing";


You just used a string literal to initialize an array.


which solves the primary problem in the original code. I'm not clear what
point you are trying to make here.

Lawrence

Nov 15 '05 #11
Lawrence Kirby wrote:

On Wed, 28 Sep 2005 06:34:39 +0000, pete wrote:
Martin Ambuhl wrote:
Then don't use string literals.
You just used a string literal
which solves the primary problem in the original code.
I'm not clear what
point you are trying to make here.


He said not to use string literals
and then he used one.

--
pete
Nov 15 '05 #12
Lawrence Kirby wrote:

On Wed, 28 Sep 2005 06:34:39 +0000, pete wrote:

There is no such thing as a "literal constant" in C.


It is a resonable description of a string literal object.


The standard lists many types of constants.
No objects are constants.

As used in a pointer initialization,
a string literal converts to an "address constant",
which would have been a better term to use.

--
pete
Nov 15 '05 #13
bh******@dodo.com.au wrote:
Thanks for that information Walter. I managed to get it working, by
allocating the memory then using strcpy to load the string.

Please read my sig.

Brian

--
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
Nov 15 '05 #14
On 28 Sep 2005 02:13:26 -0700, in comp.lang.c , "David G. Hong"
<ki****@gmail.com> wrote:
It becomes a standard function iff (if and only if) you include
<stdio.h>.
This is incorrect. What you're referring to is the fact that if you
don't include the header, the compiler may not complain about an
incompatible definition.
Although dubbed as *Standard* Input Ouput - not really a
standard.
Actually, they are - in order for a C compiler to be
Standard-compliant, it must provide these functions.
Any programmer could redefine functions already defined in
*Standard* headers.


No, this is forbidden.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-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 =----
Nov 15 '05 #15
bh******@dodo.com.au wrote on 28/09/05 :
In the following code I am trying to change the contents of a string:

int main()
{
char *string="testing";
This is not portable. The standard says that string literals are not
guaranteed to be mutable.

char const *string="testing";

is better and error prone.

rename(string);

return 0;
}

void rename(char *s)
'constness propagation' :

void rename(char const *s)
{
printf("Character 1: %c\n",*s);
*s='a';
compile error due to const. You are now warned that there is something
wrong in your design. Sure, because you are trying to modify a
read-only object.

To fix that, you must use an initiaized array of char :

char string[] = "testing";

and keep the rest of your original code ...
printf("Character 1 now: %c\n",*c);
.... well, almost... what is 'c' ? You meant 's', I guess...
}

Anyway, I am sure this is possible but for some reason I'm getting
segmentation faults at line *s='a'; when I attempt to change the value
in which *s is currently pointing to, being the first character in the
string.


Sure. Attempting to write to a string literal invokes an undefined
behaviour.

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"Clearly your code does not meet the original spec."
"You are sentenced to 30 lashes with a wet noodle."
-- Jerry Coffin in a.l.c.c++
Nov 15 '05 #16
bh******@dodo.com.au wrote:
Hi all,

In the following code I am trying to change the contents of a string:

int main()
{
char *string="testing";
The above assignment loses the const qualifier. In case you
are using gcc, -Wwrite-strings will emit warnings. Use arrays if
you want to modify content.
cat str.c #include <stdio.h>
int main (void)
{
char *string = "testing";
printf("%s\n", string);
return 0;
}which gcc gcc: aliased to gcc -Wall -W -ansi -pedanticgcc str.c
./a.out testinggcc -Wwrite-strings str.c str.c: In function `main':
str.c:4: warning: initialization discards qualifiers from pointer
target type

Karthik
rename(string);

return 0;
}


Nov 15 '05 #17

he**********************@gmail.com wrote:
in the above program what is "c", not declared in the program, first u
declare that and assign a value and then print it ok. i think that
there is no problem in the line *s='a';
so try it and send me the result.


Sorry, my apologies, *c should have read *s. I still can't figure this
one. As far as I understand, *s is a pointer, which should point to a
memory location which currently holds the value 't' (first character in
string 'testing'). Without moving the pointer, I try to reassign this
to the value 'a', but it seg. faults. I have even tried allocating
memory with malloc/memset, but still the same result.

I didn't want to use an array as I wanted to dynamically allocate
memory based on string size (at runtime). I'm sure this has been done
before without arrays and it seems logical.

Nov 15 '05 #18
Mark McIntyre <ma**********@spamcop.net> writes:
On 28 Sep 2005 02:13:26 -0700, in comp.lang.c , "David G. Hong"
<ki****@gmail.com> wrote:

[...]
Although dubbed as *Standard* Input Ouput - not really a
standard.


Actually, they are - in order for a C compiler to be
Standard-compliant, it must provide these functions.


Assuming (as we usually do around here) a hosted implementation rather
than a freestanding (embedded) implementation.

And as long as I'm nitpicking, it's the implementation, not
necessarily the compiler, that provides the standard functions.

But of course your point is correct. Since the rename() function is
provided by <stdio.h>, "rename" is reserved for use as an identifier
with external linkage. You could provide a static function called
"rename", but it would only cause confusion.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #19
bh******@dodo.com.au writes:
he**********************@gmail.com wrote:
in the above program what is "c", not declared in the program, first u
declare that and assign a value and then print it ok. i think that
there is no problem in the line *s='a';
so try it and send me the result.


Sorry, my apologies, *c should have read *s. I still can't figure this
one. As far as I understand, *s is a pointer, which should point to a
memory location which currently holds the value 't' (first character in
string 'testing'). Without moving the pointer, I try to reassign this
to the value 'a', but it seg. faults. I have even tried allocating
memory with malloc/memset, but still the same result.

I didn't want to use an array as I wanted to dynamically allocate
memory based on string size (at runtime). I'm sure this has been done
before without arrays and it seems logical.


I don't understand. Just yesterday, you wrote:

] Thanks for that information Walter. I managed to get it working, by
] allocating the memory then using strcpy to load the string.

Your original code had several problems. It declared a function
called "rename", which conflicts with the standard function of that
name. It attempted to modify a string literal (a segmentation fault
is a likely symptom in that case). And it used the name "c" rather
than "s", implying that the code you posted wasn't the actual code you
had tried.

If you're still having problems after fixing all these issues, try
posting your code again. Copy-and-paste the *exact* code that you fed
to the compiler; if you re-enter it manually, we won't be able to
guess which errors are in the original code and which are new typos.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #20
ka*****@gmail.com wrote:
bh******@dodo.com.au wrote:
Hi all,

In the following code I am trying to change the contents of a string:

int main()
{
char *string="testing";

The above assignment loses the const qualifier.


No it doesn't. One of the quirks of the C language is that it is *not*
const qualified. Modifying string literals is undefined behaviour
(forbidden) because the standard explicitly states that it is and for no
other reason.
In case you
are using gcc, -Wwrite-strings will emit warnings. Use arrays if
you want to modify content.


This is correct.
cat str.c


#include <stdio.h>
int main (void)
{
char *string = "testing";
printf("%s\n", string);
return 0;
}


There is nothing wrong with the above code. The standard does not
require a diagnostic and it does not invoke undefined behaviour.
which gcc


gcc: aliased to gcc -Wall -W -ansi -pedantic
gcc str.c
./a.out


testing
gcc -Wwrite-strings str.c


str.c: In function `main':
str.c:4: warning: initialization discards qualifiers from pointer
target type


I agree that the warning is useful. Just not required by the standard
and not provided by all compilers.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #21

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

Similar topics

9
by: Ken Godee | last post by:
I'm using the python Queue module, but since I can not find anyway to clear the Queue, I thought I would try to reassign ie...... q1 = Queue.Queue() q1.put('test1') q1.put('test2') q1.qsize()...
2
by: webdev | last post by:
I'm using the code shown below which displays 3 input fields - when you click on an input field, a DIV is displayed which allows you to select a task. On clicking the task, it is inserted into the...
4
by: songkv | last post by:
Hi, I am trying to reassign an array of char to a string literal by calling a function. In the function I use pointer-to-pointer since I want to reassign the "string array pointer" to the string...
3
by: biswaranjan.rath | last post by:
Can i do something like this: <xsl:variable name="varMaxDiffId"> <xsl:choose> <xsl:when test="$varMaxDiffId == 'NULL'"> <xsl:value-of select="-1"/> </xsl:when> <xsl:when test="$varMaxDiffId <...
23
by: Tomás | last post by:
Anything wrong with the following code?: #include <cstdlib> int main() { for (unsigned i = 0; i != 1000; ++i) { int *p = reinterpret_cast<int*>( std::rand() );
40
by: Zach | last post by:
Can someone please explain what this means and illustrate the difference with some code. Thanks, Zach
4
by: Jon Slaughter | last post by:
I'm reading a book on C# and it says there are 4 ways of passing types: 1. Pass value type by value 2. Pass value type by reference 3. Pass reference by value 4. Pass reference by reference. ...
6
by: woger151 | last post by:
If I write $x = new some_class($init_data1); and then $x = new some_class($init_data2); does the first object (constructed with $init_data1) get destroyed, or do I have to call unset() for...
6
by: Tobe | last post by:
Hi, Here's an example of something that feels like it should be OK but does in fact produce a segfault on every compiler I've tried (VC2005, g ++ 4.1.2/Linux, g++ 3.4.4/Cygwin). The line marked...
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:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...

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.