使用指向指针的指针在 C 中打印指针数组的内容 [英] Using a pointer to pointer to print the content of an array of pointer in C

查看:88
本文介绍了使用指向指针的指针在 C 中打印指针数组的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 C 语言创建了两个程序,用于打印指针数组的内容(我使用了一个指向指针的指针来打印数组的内容)在第二个程序中,我没想到会很好地打印它们,因为在 for 循环中我使用了 *p2;而不是 **p2;[来回(..;*p2;..)]我希望我的第二个程序不会在终端中打印任何内容(它永远不会找到 NULL)为什么会这样??

I created two programs in C which print the content of an array of pointers (I used a pointer to pointer to print the content of array) In the second program I did not expected to print them fine because in for loop I use *p2; instead of **p2; [fro(..;*p2;..)] I expected that my second program will not print anything in terminal (It will never find NULL) why does this happen??

#include<stdlib.h>
#include<stdio.h>

int main()
{
char *p1[100]={"jan","feb","jul","mar","apr","may","june","july","august","sept","oct","nov","dec"};
char**p2;
p2=p1;
for(p2=p1;**p2;p2++)      
   {
    
        printf("\n the words are %s",*p2);  
   }
return 0;
}

我的第二个程序:

#include<stdlib.h>
#include<stdio.h>

int main()
{
char *p1[100]={"jan","feb","jul","mar","apr","may","june","july","august","sept","oct","nov","dec"};
char**p2;
p2=p1;
for(p2=p1;*p2;p2++)      
   {
    printf("\n the words are %s",*p2);  
   }
   return 0;
}

推荐答案

第二个程序工作 p1 的初始化器比数组元素少,所以剩余的数组元素被设置为 NULL.当 p2 遍历循环时,它会检查 p2 指向的内容,即 *p2 是否为 NULL.在前 12 次迭代中的每一次迭代中,它都指向一个包含列表中字符串常量之一的地址的元素.在第 13 次迭代时,它指向一个包含 NULL 的元素,因此条件变为假.

The second program works p1 has less initializers than array elements, so the remaining array elements are set to NULL. When p2 iterates through the loop it checks if what p2 points to , i.e. *p2 is NULL. On each of the first 12 iterations it points an element containing the address of one of the string constants in the list. On the 13th iteration it points to an element containing NULL so the condition becomes false.

第一个程序触发未定义行为,因为它正在检查每个字符串的第一个字符列表,并在第 13 次迭代中取消引用一个 NULL 指针.

The first program triggers undefined behavior because it is checking the first character of each string in the list, and on the 13th iteration it dereferences a NULL pointer.

这篇关于使用指向指针的指针在 C 中打印指针数组的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆