d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Manipulating Char Pointer > C
Add Reply New Topic New Poll
Member
Posts: 27,177
Joined: Mar 27 2008
Gold: 445.00
Apr 9 2017 06:54am
I have this:

Code
char * p = (char *)&mmemory[x];
printf("%x", p);


which outputs

Code
bf8fed34


How would I go about getting two 'strings' into variables to output this

Code
printf("%s,p1);
printf("\n%s,p2);

Code
bf8f
ed34


This post was edited by ROM on Apr 9 2017 06:55am
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Apr 9 2017 08:48am
not a c expert. off-hand, i think sprintf will give you a string instead of printing to console. then you can use whatever c's substring is to separate the digits.
Member
Posts: 27,177
Joined: Mar 27 2008
Gold: 445.00
Apr 10 2017 09:12pm
Quote (carteblanche @ Apr 9 2017 10:48am)
not a c expert. off-hand, i think sprintf will give you a string instead of printing to console. then you can use whatever c's substring is to separate the digits.


Thanks for the tip. =)
Here is my solution. Don't mind the cryptic variables names. It could be cleaned up a fair bit but finally got it.

Code
char * p = (char *)&mmemory[x];
char pa[MAX_BUFFER];
sprintf(pa,"%x",p);
printf("\n\n%s",pa);
int len = strlen(pa);
int len1 = len/2;
int len2 = len - len1;
char *s1 = malloc(len1+1); // one for the null terminator
memcpy(s1, pa, len1);
s1[len1] = '\0';
char *s2 = malloc(len2+1); // one for the null terminator
memcpy(s2, pa+len1, len2);
s2[len2] = '\0';
printf("\ns1=%s",s1);
printf("\ns2=%s\n\n",s2);


This post was edited by ROM on Apr 10 2017 09:12pm
Member
Posts: 6,953
Joined: Sep 27 2003
Gold: 518.50
Apr 16 2017 11:58am
You don't need to do all that copying if you embrace crazy string formatting.
Code
#include <cstdio>

int main()
{
// this is whatever you want to look at
const char some_buffer[] = "blah blah blah";

// Need extra +1 because snprintf thinks we care about null-termination
char ptr_str[sizeof(void*) * 2 + 1];

// The "%016x" format string left-pads with zeros, which is how people usually want to look at
// pointers. The annoying use a ternary operator to work on 32- and 64-bit machines (there is
// no standard macro for doing this, although SIZEOF_VOID_P works in every Linux distro).
snprintf(ptr_str, sizeof ptr_str, sizeof(void*) == 8 ? "%016x" : "%08x", some_buffer);

// The %.*s bit is a strange output-conversion bit which says to print exactly N characters.
printf("a=%.*s\n", sizeof ptr_str / 2, ptr_str);
printf("b=%.*s\n", sizeof ptr_str / 2, ptr_str + sizeof ptr_str / 2);
}
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll