Author Topic: identical strings are showing same memory address, why?  (Read 23945 times)

Offline gauri8427

  • Single posting newcomer
  • *
  • Posts: 2
identical strings are showing same memory address, why?
« on: September 20, 2020, 02:03:06 pm »
#include<stdio.h>
#include<conio.h>
void main()
{
 printf("%u  \n","hello");
 printf("%u  \n","hello");
}

Output:-
4210688
4210688


How is the two identical strings -> "hello" have same memory address, this shouldn't be the case, they must be stored on different memory addresses.

Offline Miguel Gimenez

  • Developer
  • Lives here!
  • *****
  • Posts: 1634
Re: identical strings are showing same memory address, why?
« Reply #1 on: September 20, 2020, 02:54:53 pm »
  • 1.- This is not related to Embedded development
  • 2.- Code::Blocks is an IDE, your question is compiler-related so it is OT here
  • 3.- You are telling printf to interpret the first argument as an unsigned int but you are passing a pointer to char

Offline sodev

  • Lives here!
  • ****
  • Posts: 500
Re: identical strings are showing same memory address, why?
« Reply #2 on: September 20, 2020, 02:57:14 pm »
First of all, this question is kind of off-topic here.

Second, no, they dont need to. These are not lvalues but rvalues, they dont need to have an address at all. The compiler can freely optimize them, both are identical constant literals and it looks like the compiler decided to perform string pooling here hence they have the same address.

Offline gauri8427

  • Single posting newcomer
  • *
  • Posts: 2
Re: identical strings are showing same memory address, why?
« Reply #3 on: September 21, 2020, 10:30:06 am »
"You are telling printf to interpret the first argument as an unsigned int but you are passing a pointer to char"
Sir, here I am trying to print the address pointing to first char of string, that's why used format specifier %u because there's no point of memory adddress being negative.

Offline stahta01

  • Lives here!
  • ****
  • Posts: 7678
    • My Best Post
Re: identical strings are showing same memory address, why?
« Reply #4 on: September 21, 2020, 10:35:26 am »
gauri8427: Please read and follow the rules for this website!
http://forums.codeblocks.org/index.php/topic,9996.0.html
C Programmer working to learn more about C++ and Git.
On Windows 7 64 bit and Windows 10 64 bit.
--
When in doubt, read the CB WiKi FAQ. http://wiki.codeblocks.org