简体   繁体   English

使用带符号的char指针更改int数组的值

[英]Changing value of an int array with a signed char pointer

I want to create a function to change the value of a void array index to the specified value. 我想创建一个函数,以将void数组索引的值更改为指定的值。

I'm testing with a simple function that changes the value of the certain index using a char copy from the array (char is 1 byte). 我正在测试一个简单的函数,该函数使用数组中的char副本更改特定索引的值(char为1字节)。 I use char because I can add one to the copy to point to the next index and alter the value. 我使用char是因为我可以在副本中添加一个以指向下一个索引并更改值。

The function is: 该函数是:

void
change_value(int ** ptrs, int pos, int val) {
  char * cp = *ptrs;
  /* Assign a copy of the array */
  unsigned long int iter = sizeof(int) / sizeof(char);
  /* Store the size for every index of the array */

  for (int i = 0; i < pos; i++)
    for (unsigned long int e = 0; e < iter; e++)
      cp++;
  /* Advance to the position */

  *cp = (signed char)val;
  /* Assign the value */
}

The problem comes when I try to change the value to a -1 . 当我尝试将值更改为-1时,问题就来了。 I think the problem is because when assigning char to int the -1 is converted to a 255, so I added to the assignment the conversion to a signed char . 我认为问题是因为将char分配给int时,将-1转换为255,所以我将分配转换添加为有符号char But still with no results. 但是仍然没有结果。

The main function is: 主要功能是:

  arr[0] = 1;
  arr[1] = 2;
  arr[2] = 3;
  arr[3] = 4;
  arr[4] = 5;
  /* Create an array for values */

  change_value(&arr, 1, 0);
  /* Change value */
  for (int i = 0; i < 5; i++)
    printf("arr[%d] : %d\n", i, arr[i]);
  /* Show the array */

  printf("\n");

  change_value(&arr, 2, -1);
  /* Change value */
  for (int i = 0; i < 5; i++)
    printf("arr[%d] : %d\n", i, arr[i]);
  /* Show the array */

The output: 输出:

arr[0] : 1
arr[1] : 0
arr[2] : 3
arr[3] : 4
arr[4] : 5

arr[0] : 1
arr[1] : 0
arr[2] : 255
arr[3] : 4
arr[4] : 5

The problem is that you're not sign extending the value. 问题是您没有签署扩展价值。

int x = 0;
*((signed char *)&x) = (signed char)-1;

printf("%08x\n", -1);       // FFFFFFFF
printf("%08x\n", 255);      // 000000FF
printf("%08x\n", x);        // 000000FF

Live demo. 现场演示。

In other words, setting the value of an int to -1 requires modifying all of its bytes. 换句话说,将int的值设置为-1需要修改其所有字节。

But note that to do so you'd be relying on two implementation-defined behaviours, making this code non-portable: 但是请注意,这样做将依赖于两个实现定义的行为,从而使此代码不可移植:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM