473,804 Members | 2,190 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why wouldn't this line of give give the address of the pointer?

Given:

int main(void) {

char *ptr = "test me";
printf("%s\n", &ptr[0]);
}
Why would the output be
test me

I thought & gave the address of the pointer. Why does this yield the
string?

Nov 14 '05 #1
10 1399
ptr[0] is the first char of the string and &ptr[0] is its address, which is
what %s is expecting. Try:

printf("%lx\n", (long)&ptr);

instead :-)
Nov 14 '05 #2
grocery_stocker <cd*****@gmail. com> wrote:
Given: int main(void) { char *ptr = "test me";
printf("%s\n", &ptr[0]);
}
You're missing a return statement here, you promised that main()
returns an int, didn't you?
Why would the output be
test me I thought & gave the address of the pointer. Why does this yield the
string?


Well, 'ptr' is a pointer to the (first element of the) string. But
you have it adorned with '[0]' after it and '&' before it. And the
'[]' operator "binds" stronger than the address operator, you would
have to use parentheses to change that. So 'ptr[0]' is evaluated
first, resulting in the first element of the array. Then the '&' in
front of that makes it a pointer again to this first element. So
'ptr' and '&ptr[0]' are identical (except that in the second form
you've got to type a bit more).
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
Nov 14 '05 #3
Mick Sharpe wrote:
ptr[0] is the first char of the string and &ptr[0] is its address, which is what %s is expecting. Try:

printf("%lx\n", (long)&ptr);


Actually, this would probably be better:

printf("%p\n", (void *)&ptr);

if the representation of the pointer is not critical.

The conversion of a pointer to an integer type is implementation
defined behavior at best, undefined behavior at worst (if the pointer
cannot be represented as the specified integer type).

Rob Gamble

Nov 14 '05 #4
"Mick Sharpe" <mi*********@bt internet.com> writes:
ptr[0] is the first char of the string and &ptr[0] is its address, which is
what %s is expecting. Try:

printf("%lx\n", (long)&ptr);

instead :-)


No, don't do that. The "%lx" format expects an unsigned long
argument; you're passing a (signed) long. But that's probably not
going to cause any problems. The real problem is that you're
converting a pointer value to type long; this might or might not give
you a meaningful result.

The correct way to print a pointer is to use the "%p" format, which
expects a void*:

printf("%p\n", (void*)ptr);

The cast to void* is necessary because ptr is of type char*, and
printf with a "%p" format expects a void*. (Actually, it's not
strictly required in this case, because the language specifies that
void* and char* have the same representation, but that's a special
case and you're probably better off ignoring it.)

The above will print (some system-specific textual representation of)
the address of the memory location to which ptr points, which happens
to be the beginning of the string "test me".

Note that

printf("%p\n", (void*)&ptr);

is also legal, but does something different; it prints the address of
"ptr" itself.

--
keith Thompson (The_Other_Keit h) 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
"grocery_stocke r" <cd*****@gmail. com> writes:
Given:

int main(void) {

char *ptr = "test me";
printf("%s\n", &ptr[0]);
}
Why would the output be
test me

I thought & gave the address of the pointer. Why does this yield the
string?


The "%s" format tells printf() to expect a pointer to the first
element an array of char (to be printed as a string), and that's
exactly what you're giving it.

If you want to print the pointer value, use:

printf("%p\n", (void*)ptr);

--
Keith Thompson (The_Other_Keit h) 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 #6
On Mon, 23 May 2005 22:43:15 +0000 (UTC), "Mick Sharpe"
<mi*********@bt internet.com> wrote:
ptr[0] is the first char of the string and &ptr[0] is its address, which is
what %s is expecting. Try:

printf("%lx\n" , (long)&ptr);
The & contributes nothing to this effort. And %lx expects an unsigned
long.

instead :-)

Better still would be
printf("%p\n", (void*)ptr);
or the equivalent
printf("%p\n", (void*)&ptr[0]);

<<Remove the del for email>>
Nov 14 '05 #7
Barry Schwarz <sc******@deloz .net> writes:
On Mon, 23 May 2005 22:43:15 +0000 (UTC), "Mick Sharpe"
<mi*********@bt internet.com> wrote:
ptr[0] is the first char of the string and &ptr[0] is its address, which is
what %s is expecting. Try:

printf("%lx\n ", (long)&ptr);


The & contributes nothing to this effort. And %lx expects an unsigned
long.


The "&" takes the address of the pointer object ptr. It's not
entirely clear whether this is what the OP is looking for. He
mentioned "the address of the pointer". He probably meant the address
to which the pointer points:

printf("%p\n", (void*)ptr);

but he may literally have meant the address of the pointer object:

printf("%p\n", (void*)&ptr);

--
Keith Thompson (The_Other_Keit h) 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 #8
You're right, of course, peeps - thanks for the corrections - it's been some
years since I've written any C :-D
Nov 14 '05 #9
Got it. Thanks for the clarification.

Nov 14 '05 #10

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

Similar topics

35
10801
by: hasho | last post by:
Why is "call by address" faster than "call by value"?
8
1872
by: Dawn Minnis | last post by:
Hey guys If I have a program (see codeSnippet1) that I compile to be called test.o Then run it as test.o n n 2 3 4 I want the code to be able to strip out the two characters at the start (always going to be 2) and store them as characters. But I can't seem to get it to work because it is a pointer to a vector of characters. However, if I only run with integer arguements and use codeSnippet2 it works fine and they convert nicely to...
20
2650
by: plmanikandan | last post by:
Hi, I need to read a file line by line.each line contains different number of characters.I opened file using fopen function.is there any function to read the file line by line Regards, Mani
57
5685
by: Robert Seacord | last post by:
i am trying to print the address of a function without getting a compiler warning (i am compiling with gcc with alot of flags). if i try this: printf("%p", f); i get: warning: format %p expects type 'void *; but argument 2 has type 'void
54
24548
by: John | last post by:
Is the following program print the address of the function? void hello() { printf("hello\n"); } void main() { printf("hello function=%d\n", hello); }
14
2727
by: WStoreyII | last post by:
the following code is supposed to read a whole line upto a new line char from a file. however it does not work. it is producing weird results. please help. I had error checking in there for mallocs and ect, but i removed them to help me debug. thanks. #include <stdio.h> #include <stdlib.h> #include <string.h> void freadl ( FILE *stream, char **string ) {
6
3555
by: Kinbote | last post by:
Hi, I'm trying to make a function that opens a file, reads it in line by line, puts each line into an malloc'd array, and returns the array. I suspect I'm going about it in an atypical fashion, as I'm avoiding the use of fscanf and fgets to read in lines. I don't want to have to specify a temporary char* buffer to read in each line, and then have to concern myself with the (remote) possibility of overflows or with increasing the buffer...
6
6935
by: virgincita schmidtmann | last post by:
Good evening, I would like to pass the size of an array from the commandline. int main(int argc, int *argv) { .... max=*argv; int list; ....
36
3405
by: Julienne Walker | last post by:
Ignoring implementation details and strictly following the C99 standard in terms of semantics, is there anything fundamentally flawed with describing the use of a (non-inline) function as an address? I keep feeling like I'm missing something obvious. -Jul To keep things in context, this is in reference to describing functions to a beginner.
0
9714
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9594
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10096
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9174
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7638
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6866
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5534
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3834
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3002
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.