473,320 Members | 1,916 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,320 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 1274
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...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
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: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.