472,371 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 472,371 software developers and data experts.

Pointer problem.

hi, there,

In the following codes, If I change the varible "string "in main()
to char* string=" this is the test string "; the program will
be crashed. can someone tell me why and how to modify the code so that
I can still use char * string? thanks.

================================
#include <stdio.h>

char *Trim(char *string)
{
char *from, *to;
int spaces = 0;

/* skip leading spaces */
for (from = to = string; *from ==' '; ++from);

for (;*from != '\0'; ++from)
{
if (*from != ' ')
{
if (spaces == 1) *to++ = ' ';
spaces = 0;
*to++ = *from;
}
else spaces = 1;
}
*to = '\0';
return string;

}

int main(void)
{
char string[] = " This is a test of the
string trim ";

printf("Before: \"%s\"\n",string);

string=Trim(string);
printf("After: \"%s\"\n",string);

return 0;

}

================================================== ==========

Nov 15 '05 #1
4 1222
ajm
Hi Paul,
In the following codes, If I change the varible "string "in main()
to char* string=" this is the test string "; the program will
be crashed. can someone tell me why and how to modify the code so that
I can still use char * string? thanks.


couple of details first - the return type of Trim is a char * but is
assigned to a variable of (incomplete) type char[] which in any event
is
a string literal so I would suggest that you reserve your variable
"string"
for the input and have a separate variable, "trim_string" (of type char
*) for the output. note that a function does not know if it is passed
a char[] or a char * argument but does know what it is supposed to
return.

next a very minor detail: decide how you wish to return the trimmed
string,
do you want to use a second char ** argument and pass your trim_string
variable
by address (&trim_string) or do you want to pass the trim_string back
as the
return value. The former allows you to communicate errors via return
codes but you could also do this by returning a NULL too.

finally since you are creating a new string (trim_string) you will need
to
malloc some space for it (which requires that the caller free it when
it is no longer needed) - otherwise you are probably going to get a seg
fault or bus error etc. The rest of the trim code (def prt copy etc.)
is probably fine as is (have not studied in detail ;)

hth,
ajm.

Nov 15 '05 #2
Paul a écrit :
hi, there,

In the following codes, If I change the varible "string "in main()
to char* string=" this is the test string "; the program will
be crashed. can someone tell me why and how to modify the code so that
I can still use char * string? thanks.


What about reading the FAQ before posting ?

--
C is a sharp tool
Nov 15 '05 #3
Paul wrote:

hi, there,

In the following codes, If I change the varible "string "in main()
to char* string=" this is the test string "; the program will
be crashed. can someone tell me why
It's undefined behavior to attempt to modify the contents
of an object identified by a string literal.
Modifying most other objects of array type, is OK.
and how to modify the code so that
I can still use char * string? thanks.


char string[] is the right way to do what you want.
char *string is the wrong way to do what you want.

--
pete
Nov 15 '05 #4
ajm wrote:
Hi Paul,
In the following codes, If I change the varible "string "in main()
to char* string=" this is the test string "; the program will
be crashed. can someone tell me why and how to modify the code so that
I can still use char * string? thanks.
couple of details first - the return type of Trim is a char * but is
assigned to a variable of (incomplete) type char[] which in any event
is a string literal


You snipped a bit too much context, namely the parts of the code you are
commenting on. Please don't assume that everyone has seen the post you
are replying to. I'll restore the bits in question as by chance I happen
to have it available. The variable you referred to was in the following:

| int main(void)
| {
| char string[] = " This is a test of the
| string trim ";

string here is *not* an incomplete type, nor is it a string literal. The
C compiler completes the type because is it given an initialiser, the
string literal.

So string is an array of exactly the correct size to hold the string
literal *including* the '\0' that terminates the string.

| printf("Before: \"%s\"\n",string);
|
| string=Trim(string);

You are not allowed to assign to arrays.

| printf("After: \"%s\"\n",string);
|
| return 0;
|
| }

so I would suggest that you reserve your variable
"string"
for the input and have a separate variable, "trim_string" (of type char
*) for the output. note that a function does not know if it is passed
a char[] or a char * argument but does know what it is supposed to
return.
Correct, more or less.
next a very minor detail: decide how you wish to return the trimmed
string,
do you want to use a second char ** argument and pass your trim_string
variable
by address (&trim_string) or do you want to pass the trim_string back
as the
return value. The former allows you to communicate errors via return
codes but you could also do this by returning a NULL too.
You forgot the possibility of modifying the string in place, which
sometimes is an appropriate solution. The problems with modifying the
string in place are:

1) It means you cannot pass a pointer to a string literal, since you are
not allowed to modify string literals (it invokes undefined behaviour
which on some systems shows up as a crash and on others as weird things
happening). This is the reason the OP's program crashed when using "char
*string=" instead of "char string[]=".
2) You cannot enlarge the string.
finally since you are creating a new string (trim_string) you will need
to
malloc some space for it (which requires that the caller free it when
it is no longer needed) - otherwise you are probably going to get a seg
fault or bus error etc. The rest of the trim code (def prt copy etc.)
is probably fine as is (have not studied in detail ;)


One point you missed was that string is a bad name for a variable. At
file scope identifiers starting with str followed by a lower case letter
are reserved if string.h is included, and they are always reserved for
external linkage (even if string.h is not included), so as a matter of
course it is best to just avoid them altogether, including when they are
allowed.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #5

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

Similar topics

4
by: Carsten Spieß | last post by:
Hello all, i have a problem with a template constructor I reduced my code to the following (compiled with gcc 2.7.2) to show my problem: // a base class class Base{}; // two derived...
5
by: John N. | last post by:
Hi All, Here I have a linked list each containing a char and is double linked. Then I have a pointer to an item in that list which is the current insertion point. In this funtion, the user...
7
by: Mike D. | last post by:
I have a problem with a dynamic library I am developing, but it is really more of a pointer issue than anything else. Hopefully someone here can lend me some assistance or insight into resolving...
10
by: Kieran Simkin | last post by:
Hi, I wonder if anyone can help me, I've been headscratching for a few hours over this. Basically, I've defined a struct called cache_object: struct cache_object { char hostname; char ipaddr;...
204
by: Alexei A. Frounze | last post by:
Hi all, I have a question regarding the gcc behavior (gcc version 3.3.4). On the following test program it emits a warning: #include <stdio.h> int aInt2 = {0,1,2,4,9,16}; int aInt3 =...
7
by: Marcelo | last post by:
Hi everybody, I don't understand why I am having a problem in this code. The problem is that my pointer *phist in main method, it is declared. Then I send the pointer to my method, and this...
51
by: Joe Van Dyk | last post by:
When you delete a pointer, you should set it to NULL, right? Joe
2
by: toton | last post by:
Hi, This is continuation of topic pointer & reference doubt. http://groups.google.com/group/comp.lang.c++/browse_thread/thread/df84ce6b9af561f9/76304d7d77f6ccca?lnk=raot#76304d7d77f6ccca But I...
9
by: junky_fellow | last post by:
Hi, To print the pointer using printf(), we convert it to (void *) . printf("%p",(void *)ptr); My question is how printf() determine which type of pointer is passed to it and prints its value...
6
by: worlman385 | last post by:
For pointer and non-pointer initialization of an object like MyCar mycar; MyCar* mycar = new MyCar(); I heard from other people saying if object i create must live outside scape, then I use...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
1
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
0
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.

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.