简体   繁体   English

如何访问C中数组内部的指针的索引?

[英]How do I access an index of a pointer inside of an array in C?

If I have the following code: 如果我有以下代码:

char test[3] = {11,22,33};
char *ptr, *ptr2;
char *array[2] = {ptr,ptr2};

How do I access the number 22 through the array? 如何通过数组访问数字22?

I've tried the following with no success: 我已经尝试了以下方法,但均未成功:

array[0][1]

But if I access the pointer variable through the the write() function, like: 但是,如果我通过write()函数访问指针变量,例如:

write(file, array[0], 3)

It will write 112233 to the file no problem. 它将112112写入文件没有问题。 I just want to access the 1 index though. 我只想访问1索引。

in

  char *ptr, *ptr2; char *array[2] = {ptr,ptr2}; 

you missed to initialize ptr and ptr2 您错过了初始化ptrptr2的机会

note also ptr and ptr2 are not constant initializer element 还要注意ptrptr2不是常量初始值设定项元素

do

char test[3] = {11,22,33};
char *ptr = test, *ptr2 = NULL; /* ptr2 initialized even though not important for array[0][1] */
char *array[2];

array[0] = ptr;
array[1] = ptr2;

and array[0][1] will be 22 并且array[0][1]将为22


I encourage you to compile with options to produce warning/error, and of course to take them into account to finally have no warning/error indicated by the compiler. 我鼓励您使用产生警告/错误的选项进行编译,当然要考虑到它们,最终编译器不会指示警告/错误。

If I compile your code with options I get : 如果我使用选项编译您的代码,则会得到:

pi@raspberrypi:~ $ cat a.c
int main()
{
  char test[3] = {11,22,33};
  char *ptr, *ptr2;
  char *array[2] = {ptr,ptr2};

  return array[0][1];
}
pi@raspberrypi:~ $ gcc -pedantic -Wextra a.c
a.c: In function ‘main’:
a.c:5:9: warning: ‘ptr’ is used uninitialized in this function [-Wuninitialized]
   char *array[2] = {ptr,ptr2};
         ^~~~~
a.c:5:9: warning: ‘ptr2’ is used uninitialized in this function [-Wuninitialized]

But : 但是:

pi@raspberrypi:~ $ cat aa.c
#include <stdio.h>

int main()
{
  char test[3] = {11,22,33};
  char *ptr = test, *ptr2 = NULL; /* ptr2 initialized even not important for array[0][1] */
  char *array[2];

  array[0] = ptr;
  array[1] = ptr2;

  printf("%u\n", (unsigned char) array[0][1]);
}
pi@raspberrypi:~ $ gcc -pedantic -Wextra aa.c
pi@raspberrypi:~ $ ./a.out
22
pi@raspberrypi:~ $ 

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

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