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

时间:2019-03-15 19:44:38

标签: c

如果我有以下代码:

<div class="col-md-6">
                            <div class="form-group">
                                <label>Vos Assurances</label>
                                 {% for item in medecin.assurance %}
                                      {% if item is not empty %}
                                <input type="text" class="form-control" readonly
                                       placeholder="{{ item.nom|upper }} ">
                                       {% else %}
                                       <input type="text" class="form-control" readonly
                                       placeholder="Vous n'avez pas d'assurance ">
                                       {% endif %}
                                       {% endfor %}
                            </div>
                        </div>

如何通过数组访问数字22?

我尝试以下操作均未成功:

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

但是,如果我通过write()函数访问指针变量,例如:

array[0][1]

它将把112233写入文件没问题。我只想访问1索引。

1 个答案:

答案 0 :(得分:3)

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

您错过了初始化 ptr ptr2

的操作

还请注意 ptr ptr2 不是常量初始值设定项元素

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;

array[0][1]将为22


我鼓励您编译产生警告/错误的选项,当然也要考虑到它们,最终编译器不会指示警告/错误。

如果我使用选项编译您的代码,则会得到:

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]

但是:

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:~ $