Changing int value using char pointer

assign integer value to char pointer in c
char pointer to int
can char pointer point to integer
char pointer to int pointer c
how to store a string in char pointer in c
char pointer array in c
char pointer to char array
character pointer to integer in c

Why does this code print 10 = -246 instead of 10 = 10? Does the pointer size matter?

#include <stdio.h>

int main() {
    int i = 10;
    int j = -1;

    char *p, *q;

    p = (char*) &i;
    q = (char*) &j;

    *q = *p;

    printf("%d = %d\n", i, j);

    return 0;
}

First of all, the result here depends on CPU endianess. You appear to have a little endian CPU.

Assuming int is 32 bit 2's complement, -1 is stored in 4 bytes as 0xFFFFFFFF. A char access only affects one byte. Since you have little endian, it will be the least significant byte in your case. This byte will get overwritten with the value 10, 0x0A. You end up with 0xFFFFFF0A which is the 2's complement representation of -246.


Please note that the char type has implementation-defined signedness and should therefore always be avoided when doing bit/byte manipulations. Use uint8_t instead.

Also note that accessing one data type through a pointer of a different type is risky and poorly-defined, in all other cases than when using character types specifically (uint8_t is a character type), because they are an exception to the "strict aliasing rule".

Character Array and Character Pointer in C, The type of both the variables is a pointer to char or (char*) , so you can it will always point to the address 2000 , we can't change its address. We can assign a new string to arr by using gets() , scanf() , strcpy() or by assigning characters one by one. Here ptr is uninitialized an contains garbage value. Using a Pointer to Change a Variable’s Value. We can use pointers in many ways. For example, we can use a pointer to change the value of a variable. Let’s learn more about pointers. When we use *point, we are dereferencing the pointer. This means that we are giving the value of the variable, instead of the value of the pointer.

Does the pointer size matter?

No, the size of the pointer doesn't matter. What matter is the type of pointer, i.e. the type it points to.

The number of bytes copied when assigning through a pointer depends on the pointer type. If the pointer type is a char pointer, it will copy sizeof(char) bytes. If the pointer type is an int pointer, it will copy sizeof(int) bytes.

Why does this code print 10 = -246 instead of 10 = 10?

It's system dependent. Since you get this result, you are probably on a little endian system which means that data in memory is stored with LSB first (i.e. a pointer to a variable points to LSB of that variable).

So what happens in your code is that LSB of variable i is copied to LSB of variable j. Since sizeof(int) is more than 1, you'll not end in a situation where i and j are equal. Simply because you didn't copy all bytes of i into j.

Assuming a 32 bit int it may look like:

Coding resources, cat main.c #include <stdio.h> int main(void) { printf("The size of an int pointer is % ld sizeof(char *)); printf("The size of a char pointer is %ld bytes!\n", sizeof(int *)) Couldn't we have just used num directly to change its value from 7 to 8? Live Example of Pointer Accessing : Suppose we assign the address of integer variable to the character pointer then some part of value will be lost while accessing the variable using character data type. # include < stdio.h > int main {int a = 320; char * ptr; ptr = (char *) & a; printf (" %d ", * ptr); return (0);} Output of the Code : 64

Assume the CPU is 32bit.

First question: why print 10 = -246

i = 10;  (0x0000 000A)
j = -1;  (0xFFFF FFFF) Two's Complement

*q pointer to the lowest 8bit of integer j, after *q = 10;, j becomes 0xFFFF FF0A which is the Two's Complement of -246

refer How Computers Represent Negative Binary Numbers?

Second question: does the pointer size matter?

Yes, covert int pointer to char pointer will lose the 24bit data in this case.

C Strings (Arrays vs. Pointers), This means that when we use a char * to keep track of a string, the character void SomeFunc(int length) { char *str; // Don't forget extra char for nul We keep track of the dynamically-allocated array with a pointer (e.g., the return value of the � Note that the text pointer parameter in changeText points to a const char. Therefore, you cannot change the string in the calling function through it, so the comment "make character a space" is illogical.

Here p & q is a char pointer. p = (char*) &i; So p will point to the first byte of the integer var i which is of 4 bytes. So on dereferncing p you will get 10(00001010).

q = (char*) &j; As j = -1, it is the largest negative no. It means j var will have all 1's in 32 bits(11111111 11111111 11111111 11111111)

*q = *p; In this line you are copying the lowest first byte(00001010) from i's location to j's location first byte because both pointers are of char *. So now after copying, value in j's location will be: 11111111 11111111 11111111 00001010 which is equivalent to -246. Calculate the 2's complement of 11111111 11111111 11111111 00001010. It will give you -246.

Pointer Basics and Pass-By-Address, Now that p is declared as a pointer to an int, the variable p stores the address. int * ip; char * cp; double * dp; It contains some random value from memory right now, because we haven't initialized it. offers another method of allowing us to change the original argument of a function (like with Pass By Reference). The type of both the variables is a pointer to char or (char*), so you can pass either of them to a function whose formal argument accepts an array of characters or a character pointer. Here are the differences: arr is an array of 12 characters. When compiler sees the statement:

You have to do a casting like this to have the value of i in j: * (int*)p = * (int*)q It will convert the type of your pointer and you are going to "transfer" the value of i in j.

Or in addition you can do it without casting using a for loop loke this: `

for(int k=0; k<sizeof(int);k++){
    *(p+k) = *(q+k);
}

` With this loop you are going to write every single bit of i in every byte of k one byte at time. This because int have a 4 byte structure and char have a 1 byte structure.

Pointer Basics, double * dptr; // a pointer to a double char * c1; // a pointer to a character float All three of these declare the variable p as a pointer to an int. you are ready to use them (i.e. with valid targets), so that their values are known. As with other data types, you can always force a coercion by performing an explicit cast operation. Similarly, if ch is a character variable, then &ch will return a char pointer value. Note - The operand of & operator is as ordinary available but operand of ∗ is a pointer variable. Using '∗' operator, changing/accessing value being pointed to by pointer (its state) is called Dereferencing.

Pointers in C Programming with examples, Pointers in C with examples: A Pointer holds the address of another variable. # include <stdio.h> int main() { int num = 10; printf("Value of variable num is: int * p1 /*Pointer to an integer variable*/ double *p2 /*Pointer to a variable of data type double*/ char The statement above will change the value of a from 10 to 200. Compliant Solution. Any valid pointer to void can be converted to intptr_t or uintptr_t and back with no change in value. (See INT36-EX2.).) The C Standard guarantees that a pointer to void may be converted to or from a pointer to any object type and back again and that the result must compare equal to the original pointer.

C/Pointers, 1 int *pointerToInt; 2 double *pointerToDouble; 3 char *pointerToChar; 4 char You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void � Dereferencing can be used to either indirectly get a value from the pointer address or to assign a value to the pointer address. Let’s look at an example. #include <stdio.h> int main(int argc, char **argv) { // declare int ival and int pointer iptr.

4. Type Conversions - C in a Nutshell [Book], For example, a pointer to a structure can be converted into a different pointer type . You can also convert values from one type to another explicitly using the cast operator (see Chapter 5): _Bool < char < short < int < long < long long. In the above example, since p stores the address of name[0], therefore the value of *p equals the value of name[0] i.e., 'S'. So in while loop, the first character gets printed and p++ increases the value of p by 1 so that now p+1 points to name[1]. This continues until the pointer reaches the end of the string i.e., before *p becomes equal to

Comments
  • The int is made up of several bytes (char is one byte) ... if you want to copy the value then you need to copy all of the bytes, not just 1
  • uint8_t may or may not be a character type, unfortunately. There could be an extended integer type defined with 8 bit size (reference)
  • @M.M Nah that doesn't make sense in the real world. If uint8_t exists, then so does 8 bit char. It would then be utterly stupid of the compiler implementation to map uint8_t to anything but unsigned char. And even if it was possible to map it to some extended non-standard type, such a compiler would become useless and die out, since nobody wants to use a useless compiler.
  • I tried to add this loop and it solved the problem but i don't know if it's a best way to do it; for(int k = 1; k <= 3; k++) q[k] = (char)NULL;
  • Before going for the solution, first of all what you want to achieve in this program? for(int k = 1; k <= 3; k++) q[k] = (char)NULL; This line is ideally setting last 3 bytes to NULL i.e. Zero. Instead you can initialize the j var with zero.
  • The exercise here is printing 10 = 10 without assigning new numbers directly to the int variables but working only in char pointers
  • Better you ca use memset after printf statement to zeroed the next 3 bytes. memset(q+1, 0, 3);