Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

int pointer to char array

Posted on 2006-04-21
19
Medium Priority
?
792 Views
Last Modified: 2010-05-18
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
0
Comment
Question by:nstefanov
  • 6
  • 4
  • 3
  • +3
18 Comments
 
LVL 20

Expert Comment

by:ikework
ID: 16508612
int * ptr1 = reinterpret_cast<int*>( test );

or

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


hope it helps :)
ike
0
 
LVL 20

Expert Comment

by:ikework
ID: 16508625
or the c-ast-way:

int * ptr1 =(int*)test;

or

int * ptr1 =(int*)&test[0];
0
 
LVL 20

Expert Comment

by:ikework
ID: 16508631
oops typo -->> c-cast ... ;))
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 53

Expert Comment

by:Infinity08
ID: 16508716
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
 
LVL 22

Accepted Solution

by:
grg99 earned 500 total points
ID: 16508718


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
 
LVL 9

Expert Comment

by:jhshukla
ID: 16508747
>> 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
 
LVL 9

Expert Comment

by:jhshukla
ID: 16508760
oops. grg99 got there first.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 16508786
heh, and I got there even earlier lol ... 06:11, 06:11, 06:13 ... lol ... seems to be that hour of the day :)
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16509355
>>>>  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
 
LVL 53

Expert Comment

by:Infinity08
ID: 16509780
>> 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
 
LVL 9

Expert Comment

by:jhshukla
ID: 16510279
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
 

Author Comment

by:nstefanov
ID: 16510525
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
 
LVL 53

Expert Comment

by:Infinity08
ID: 16510787
>> 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
 
LVL 9

Expert Comment

by:jhshukla
ID: 16510851
call changefunction like changefunction((int)&test[0], (int)(test+strlen(test))). -1 from lastaddress if you dont want to include trailing null character.
0
 

Author Comment

by:nstefanov
ID: 16510993
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
 
LVL 9

Expert Comment

by:jhshukla
ID: 16511066
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
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16512926
>>>> 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
 
LVL 9

Expert Comment

by:jhshukla
ID: 16512981
>> 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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

580 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question