简体   繁体   English

char数组中的C指针

[英]C pointer in char array

I am trying to understand if my solution to a problem I have is possible, I want to add a pointer to an array member of a stack allocated array so that the array member is dynamically changeable.我试图了解我是否可以解决我遇到的问题,我想添加一个指向堆栈分配数组的数组成员的指针,以便该数组成员可以动态更改。

Has to be an unsigned char as this is a comms buffer.必须是无符号字符,因为这是一个通讯缓冲区。

int main() {
    unsigned char *var;
    unsigned char test[] = {*var, 0x34, 0x56, 0x78};
    *var = 0x12;
    printf("%x %x %x %x %x", *var, test[0],test[1],test[2],test[3]);
    *var = 0xff;
    printf("%x %x %x %x %x", *var, test[0],test[1],test[2],test[3]);
}

Thanks for any answers either yay or nay.感谢您的任何回答,是或否。

edit: Thanks for all the suggestions, I had looked at using array indexes before trying to find a different method.编辑:感谢所有建议,在尝试找到不同的方法之前,我已经研究过使用数组索引。 The issue is that there is no way to know the array index as the array that is being edited is concatenated to form a larger array so the index changes which is why I wanted to use a variable.问题是没有办法知道数组索引,因为正在编辑的数组被连接起来形成一个更大的数组,所以索引发生了变化,这就是我想使用变量的原因。

You have it almost.你几乎拥有它。 Try this:尝试这个:

int main()
{
    unsigned char* var;
    unsigned char test[] = { 0x00, 0x34, 0x56, 0x78 };
    var = &test[0];  // Makes var point to the first test[] item
    *var = 0x12;
    printf("%x %x %x %x %x\n", *var, test[0], test[1], test[2], test[3]);
    *var = 0xff;
    printf("%x %x %x %x %x\n", *var, test[0], test[1], test[2], test[3]);
}

The problem you have is that you do not understand what the pointer is.你的问题是你不明白指针是什么。

    unsigned char* var;
    unsigned char test[] = { 0x00, 0x34, 0x56, 0x78 };

This invokes undefined behaviour.这会调用未定义的行为。 var is the pointer to char but does not point anywhere (it is not initialized or saying other way it has no assigned reference). var是指向 char 但不指向任何地方的指针(它没有被初始化或以其他方式说它没有分配的引用)。 The second definition simple takes the char value referenced by this pointer (which does not point to any valid character) and places this value as the first element of the array test .第二个定义 simple 获取这个指针引用的 char 值(它不指向任何有效字符)并将这个值作为数组test的第一个元素。 The array itself does not hold any information that about the sources of the data stored.数组本身不包含有关所存储数据来源的任何信息。

To make this code working you need to assign the pointer with the reference of the first element of the array.要使此代码正常工作,您需要为指针分配数组第一个元素的引用。

int main(void)
{
    unsigned char test[] = { 0x00, 0x34, 0x56, 0x78 };
    unsigned char* var = test;  /* or &test[0] */

    *var = 0x12;
    printf("%x %x %x %x %x\n", *var, test[0], test[1], test[2], test[3]);

    *var = 0xff;
    printf("%x %x %x %x %x\n", *var, test[0], test[1], test[2], test[3]);
}

Minor problem: your main declaration is invalid.小问题:您的main声明无效。 It has to be int main(void)它必须是int main(void)

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

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