int pointer to char array

How do I create an int pointer to an array of chars;

Something like this:

char test [] = "hello";

int * ptr1 = &test[0];

Basically the first charater of test.  Then I want to be able to say ptr = ptr + 2 and ptr would then point to l.  Thanks
nstefanovAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ikeworkCommented:
int * ptr1 = reinterpret_cast<int*>( test );

or

int * ptr1 = reinterpret_cast<int*>( &test[0] );


hope it helps :)
ike
0
ikeworkCommented:
or the c-ast-way:

int * ptr1 =(int*)test;

or

int * ptr1 =(int*)&test[0];
0
ikeworkCommented:
oops typo -->> c-cast ... ;))
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Infinity08Commented:
But that doesn't allow you to do this :

>> Then I want to be able to say ptr = ptr + 2 and ptr would then point to l.

!!

the size of an int is generally 4 bytes, while the size of a char is 1 byte ... so, adding 1 to an int pointer will jump ahead 4 bytes, thus pointing to 'o', and not to 'e'.

Why do you want an int array ? Just because you need the ASCII values of the characters in a string ? If so, here's how to get it into an int :

   char *test = "hello";
   int ascii_val = (int) test[1]; // ascii value of the second character in the test string

No need to convert it to an integer array !
0
grg99Commented:


Basically the first charater of test.  Then I want to be able to say ptr = ptr + 2 and ptr would then point to l.  Thanks


you cant say  int* ptr;   well  you can, but it wont do what you want.  hat's because once you force a pointer to be a differnt type, the pointer indexing and increment operators will bump by that datatype width.  so ptr1++ will point to 2, 4, or 8 bytes farther ahead.   Plus if you try to derefeence the pointer *ptr1 will grab 2,4, or 8 bytes frot he string.  Not probably what you want.

if you want to get at the bytes as ints, that's easy-- they already are bytes, so just do:

char * cp = &text;
int  intval;

intval = *cp ;  // intval will have an integer value of the first chaacter.

cp++;  // now point to next

intval = *cp;  // intval will have the second character.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jhshuklaCommented:
>> Then I want to be able to say ptr = ptr + 2 and ptr would then point to l.  Thanks
that won't work. ptr = ptr + x really adds x*sizeof(*ptr) to ptr. casting is fine but pointer arithmetic is wrong. you will have to cast ptr to int or char*, add and then recast to ptr.
ptr = (int*)((int)ptr+2) OR ptr = (int*)((char*)ptr + 2)
i prefer the second method because there is portability issue with first method in case of 64bit systems.
0
jhshuklaCommented:
oops. grg99 got there first.
0
Infinity08Commented:
heh, and I got there even earlier lol ... 06:11, 06:11, 06:13 ... lol ... seems to be that hour of the day :)
0
itsmeandnobodyelseCommented:
>>>>  How do I create an int pointer to an array of chars;

Don't like castings (and don't like people showing how to cast a char array to a int pointer what is nonsense).

Actually, your task can be properly solved without casting:

   char test [] = "hello";                    // that's a char array of size 6 bytes

   int * ptr1 = new int[sizeof(test)];    // creates an int array of size 6 integers (each of them 4 bytes)

   for (int i = 0; i < sizeof(test); ++i)
         ptr1[i] = test[i];    // no need to cast anything

   for (int n = 0; n < sizeof(test); ++n)
       cout << " char == " << test[i] <<  " int == " << ptr1[i] << endl;

   delete [] ptr1;  // free storage

Note, char is a 1 byte signed integer. Codes 0 to 127 were called ASCII characters and only 7 low bits were used for that. ASCII codes plus codes from -128 to -1  (or 128 to 255 interpreting it as unsigned chars) were called ANSI characters using all 8 bits of a byte. ASCII Codes 0 to 31 and 127 are not printable. That's why the last char showed as int == 0 won't print as a char. It's the terminating zero character that signals text end.

int is  a 32bit integer. When assigning a 8bit signed integer to a 32bit signed integer the sign bit (bit 7 in a char) gets interpreted. Thus, the int gets a negative value when assigning chars of the upper part of the ANSI code table, e. g. the new '€' (EURO) character which got ANSI code 128 (or -128 if looked at it as a signed integer).

Regards, Alex
0
Infinity08Commented:
>> Don't like castings
Except when the alternative involves a lot of memory copies (like copying an entire char array into another int array) - especially when there's no need to copy at all since the data is exactly the same except for the format it's stored in.

btw :

>>         ptr1[i] = test[i];    // no need to cast anything

Can you explain to me how this doesn't cast ? As far as i can see, this casts a char to an int ...

So ... to summarise, there's NO need to create a new array, let alone to cast the entire array to some other type (which would be quite impractical in this case). Just use test[i] as an integer if you need its ANSI value (thanks for correcting Alex), or as a char if you need it as a character.
0
jhshuklaCommented:
i agree with infinity but alex meant manual, hard-coded cast. i don't understand why he doesn't like casts. interally they are all 4 byte numbers. doesn't make a difference to the machine.

@nstefanov: why do you need to do assign address of char to an int *?
0
nstefanovAuthor Commented:
Thanks for all of your input.  I am trying something like this:

char test [] = "hello";

char * cp = &test;
int  intval;
intval = *cp;

And it will not compile :  cannot convert from char to char *.

The reason I need this is that i need to pass the first address and last address of my char array test to a function which accepts two integers like this:

int changefunction(int firstaddress, int lastaddress)
{
   if (firstaddress == rightaddress)
      do something
   else
     do something else like change righaddress to = righaddress - (the address of some other position in the original string)
   return something like the int value contained at original string at firstaddress

Thanks!

0
Infinity08Commented:
>> And it will not compile :  cannot convert from char to char *.

Either use :

    char * cp = test;

or :

    char * cp = &test[0];

>> The reason I need this is that i need to pass the first address and last address of my char array test to a function which accepts two integers like this
I'm not sure of what you want ... why do you need to convert the char array to an int array to achieve this ?
0
jhshuklaCommented:
call changefunction like changefunction((int)&test[0], (int)(test+strlen(test))). -1 from lastaddress if you dont want to include trailing null character.
0
nstefanovAuthor Commented:
I don't want to convert the char array.  All I want to do is be able to pass the first address of the char array and last address of the char array into my function.  Then in my function i need to be able to change the addresses ie(change the last address to middle of string in effect halfing the string).  Is there a better way to do that?
0
jhshuklaCommented:
that is what the changed function call does. here is the break down:
test[0] -> take its address -> cast as int
test /*address of test[0]*/ -> add string length to it -> gives address of '\0' -> cast to int

IMO it would be better if your function took in char * as addresses. will it impact a lot of other code if you changed the prototype?
0
itsmeandnobodyelseCommented:
>>>> to pass the first address of the char array and last address of the char array

   char test[] = "Hello";
   int firstaddress = reinterpret_cast<int>(&test[0]);
   int lastaddress = reinterpret_cast<int>(&test[sizeof(test)-1]);
   changefunction(firstaddress , lastaddress );

Note, '&test[0]' is equivalent to 'test' cause the address of the first array element has the same value as the pointer to the char array and the pointer is equivalent to the array beside of the pointer has a size of 4.

  char   test[] = "Hello";
  char* test1  = test;        
  char* test2  = &test[0];  

test and test1 and test2 have the same value what is the address of the first character of the text string.

>>>> (int)(test+strlen(test))

Actually the last character of the array is '&test[sizeof(test)-1]' . strlen only gives the length of the text string what might be less (or even greater if the terminating zero character was overwritten).

  char test[20] = "Hello";

Here the last character of the array is byte 20 (base 1) what should have value '\0' at most compilers (repeating the last value filled by the initialization). To go for sure you have to do

  char test[20] = { '\0' };
  strcpy(test, "Hello");

But:

  char test[20] = { ' ' };
  strncpy(test, "Hello", strlen("Hello"));

That wouldn't set a terminating zero character to test that was initialized with all spaces. Hence

    strlen(test) >= 20

is true. strlen would run beyond the array bounds until it reached (by incident) the first zero character.

>>>>  if (firstaddress == rightaddress)

That never happens beside you would create an empty string.

   char test[] = "";   // size is 1

>>>> to a function which accepts two integers

I fully agree with jhshukla. If needing addresses in a function you should define the arguments as char* or const char* and not as int.

>>>> i don't understand why he doesn't like casts

In C++ there are only rare cases where you really need casts. One is if you have to use an interface that has different types than the ones you are using, e. g. 'unsigned int' instead of an 'int'. If you *know* that your integers were not negative these casts give no problems, though you should try to avoid them nevertheless if possible. A second 'valid' cast might be a dynamic cast where you got a baseclass pointer or baseclass reference but need the derived type. However, that most likely violates the principle of encapsulation (when getting a baseclass pointer you shouldn't have to *know* what is the derived class). I wouldn't cast but would try to get the required functioniality by calling a virtual function. Virtual function calls are the C++ way to *cast* a baseclass object to the required derived object.
 
Regards, Alex


   
 
0
jhshuklaCommented:
>> One is if you have to use an interface that has different types than the ones you are using
i would avoid casts but isn't the interface the problem here? unless of course nstefanov changes the prototype.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.