473,325 Members | 2,480 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,325 software developers and data experts.

string initilization WHY?

Why would this work? - and it does! any thoughts?

#include<stdio.h>

void init(char **str){ *str="Awesome"; }

main(){
char * str;

printf("address: %d\n", str);
init(&str);
printf("address: %d\n", str);
printf("string:\'%s\' has %d characters \n", str,strlen(str));
}

Nov 14 '05 #1
7 1529

puzzlecracker wrote:
Why would this work? - and it does! any thoughts?

#include<stdio.h>

void init(char **str){ *str="Awesome"; }

main(){
char * str;

printf("address: %d\n", str);
init(&str);
printf("address: %d\n", str);
printf("string:\'%s\' has %d characters \n", str,strlen(str));
}


read this: http://www.ishiboo.com/~nirva/c++/stl-ref/lib_prin.html
There is more to printf than %d. There is more to C than printf.

Nov 14 '05 #2

Kobu wrote:
puzzlecracker wrote:
Why would this work? - and it does! any thoughts?

#include<stdio.h>

void init(char **str){ *str="Awesome"; }

main(){
char * str;

printf("address: %d\n", str);
init(&str);
printf("address: %d\n", str);
printf("string:\'%s\' has %d characters \n", str,strlen(str));
}


read this: http://www.ishiboo.com/~nirva/c++/stl-ref/lib_prin.html
There is more to printf than %d. There is more to C than printf.


My question is COMPLETELY DIFFERN. I am asking why string is being
copied!!!!!!!!!!!!!!!!!!

Nov 14 '05 #3
puzzlecracker wrote:
puzzlecracker wrote:
Why would this work? - and it does! any thoughts?
And why should it not?
#include<stdio.h>
void init(char **str){ *str="Awesome"; }
main(){
You really ought to specify the return type -- int -- for main(). You
can get away with leaving it out in C90 (where it is implicitly int),
but C99 does away with implicit int.


char * str;

printf("address: %d\n", str);
init(&str);
printf("address: %d\n", str);
printf("string:\'%s\' has %d characters \n", str,strlen(str));
You really ought not omit returning a value (0, EXIT_SUCCESS, or
EXIT_FAILURE) from main. In C99 'return 0;' is implicit, but it isn't
in C90.
}
My question is COMPLETELY DIFFERN. I am asking why string is being
copied!!!!!!!!!!!!!!!!!!


It isn't! Why do you think it is? The address of the string literal
"Awesome" is being stored in the pointer str.

Nov 14 '05 #4
"puzzlecracker" <ir*********@gmail.com> writes:
Why would this work? - and it does! any thoughts?

#include<stdio.h>

void init(char **str){ *str="Awesome"; }

main(){
char * str;

printf("address: %d\n", str);
init(&str);
printf("address: %d\n", str);
printf("string:\'%s\' has %d characters \n", str,strlen(str));
}


It "works" because behaving as you expect is one of the infinitely
many possible consequences of undefined behavior.

Here's a corrected version of your program that (almost) avoids the
undefined behavior:

#include <stdio.h>
#include <string.h>

void init(char **str){ *str="Awesome"; }

int main(void)
{
char *str;
printf("address: %p\n", (void*)str);
init(&str);
printf("address: %p\n", (void*)str);
printf("string:\'%s\' has %d characters \n", str, (int)strlen(str));
return 0;
}

I say "almost" because it still uses the value of an unitialized (and
therefore indeterminate) variable in the first printf() call.

You could probably get away without the void* casts, since void* and
char* are effectively compatible as parameters, but IMHO it's good
style to use it anyway. (I've argued before that all casts should be
considered suspicious. Arguments to printf-like functions are a rare
case where casts are often required, because there is no implicit
conversion to the proper type.)

But as you said elsewhere in this thread, none of the problems I
corrected are directly relevant to what you're asking about.

The variable str is a pointer to char; effectively it points to a
string. The init() call changes the value of str, so it points to a
string whose value is "Awesome" (with a trailing '\0', of course).
(The string itself isn't copied.) This string is statically
allocated, so there's no problem referring to it after leaving the
init() function.

--
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 14 '05 #5

"Keith Thompson" <ks***@mib.org> schreef in bericht
news:ln************@nuthaus.mib.org...

I saw this line.
printf("string:\'%s\' has %d characters \n", str, (int)strlen(str));


Having been in this group before I know that the cast to int is put in there
deliberately. But why is that?
It doesn't avoid any errors and it makes the code (a little) harder to read
I'd say
Nov 14 '05 #6
"Servé La" wrote:

"Keith Thompson" <ks***@mib.org> schreef in bericht
news:ln************@nuthaus.mib.org...

I saw this line.
printf("string:\'%s\' has %d characters \n", str, (int)strlen(str));
Having been in this group before I know that the cast to int is put in there
deliberately. But why is that?


It's because we must be sure that the format specifier correctly
describes the type of its matching parameter. strlen returns a
size_t, not an int. Because the Standard doesn't give us a format
specifier for a size_t (in C90, at least), we must convert the
value into a type we know we can print.
It doesn't avoid any errors
Wrong. It avoids the error of sending an unmatchable type to a printf
call in a C90 program.
and it makes the code (a little) harder to read
I'd say


Yes, it does, but that's sometimes the price you pay for correctness.
(Often, it's the other way around; correct code is /more/ readable
than incorrect code.)
Nov 14 '05 #7
"infobahn" <in******@btinternet.com> wrote in message
news:41***************@btinternet.com...
"Servé La" wrote:

"Keith Thompson" <ks***@mib.org> schreef in bericht
news:ln************@nuthaus.mib.org...

I saw this line.
printf("string:\'%s\' has %d characters \n", str,
(int)strlen(str));
Having been in this group before I know that the cast to int is put in there deliberately. But why is that?
It's because we must be sure that the format specifier correctly
describes the type of its matching parameter. strlen returns a
size_t, not an int. Because the Standard doesn't give us a format
specifier for a size_t (in C90, at least), we must convert the
value into a type we know we can print.


Correct. But I like to use 'unsigned long', which is the largest
unsigned integer type (common to C89 and C99), more likely to be able to
represent more of the range of 'size_t'. (Since C89 seems to still be
more prevalent, I still use it as my 'common denominator' for writing
C code).
It doesn't avoid any errors


Wrong. It avoids the error of sending an unmatchable type to a printf
call in a C90 program.
and it makes the code (a little) harder to read
I'd say


Yes, it does, but that's sometimes the price you pay for correctness.
(Often, it's the other way around; correct code is /more/ readable
than incorrect code.)


If you find the 'printf()' call too 'ugly', you could separate
the conversion into another statement:

unsigned long len = (unsigned long)strlen(str); /* put string length into
a 'printf-able' type */

printf("%lu\n", len); /* 'clean' call to printf()' */

-Mike
Nov 14 '05 #8

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

Similar topics

16
by: Krakatioison | last post by:
My sites navigation is like this: http://www.newsbackup.com/index.php?n=000000000040900000 , depending on the variable "n" (which is always a number), it will take me anywhere on the site......
5
by: Stu Cazzo | last post by:
I have the following: String myStringArray; String myString = "98 99 100"; I want to split up myString and put it into myStringArray. If I use this: myStringArray = myString.split(" "); it...
9
by: John F Dutcher | last post by:
I use code like the following to retrieve fields from a form: recd = recd.append(string.ljust(form.getfirst("lname",' '),15)) recd.append(string.ljust(form.getfirst("fname",' '),15)) etc.,...
20
by: Pierre Fortin | last post by:
Hi! "Python Essential Reference" - 2nd Ed, on P. 47 states that a string format can include "*" for a field width (no restrictions noted); yet... >>> "%*d" % (6,2) # works as expected ' ...
9
by: Derek Hart | last post by:
I wish to execute code from a string. The string will have a function name, which will return a string: Dim a as string a = "MyFunctionName(param1, param2)" I have seen a ton of people...
10
by: Angus Leeming | last post by:
Hello, Could someone explain to me why the Standard conveners chose to typedef std::string rather than derive it from std::basic_string<char, ...>? The result of course is that it is...
37
by: Kevin C | last post by:
Quick Question: StringBuilder is obviously more efficient dealing with string concatenations than the old '+=' method... however, in dealing with relatively large string concatenations (ie,...
2
by: Andrew | last post by:
I have written two classes : a String Class based on the book " C++ in 21 days " and a GenericIpClass listed below : file GenericStringClass.h // Generic String class
6
by: puzzlecracker | last post by:
Why would this work? - and it does! any thoughts? #include<stdio.h> void init(char **str){ *str="Awesome"; } main(){
5
by: vsnadagouda | last post by:
Hello All, I am looking for some way to delay the global variable initilization. To make myself more clear, here is a simple example: +++++++++++++++++++++++++++++++++++++++++++++++++++++++++...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
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: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
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
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...

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.