使用指针显示数组的内容 [英] using pointers to display content of array

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

问题描述

我对如何使用指针显示数组感到困惑.我可以使用for循环使用数组轻松地做到这一点,但是我有兴趣知道如何通过指针使用它,而我很执迷于如何计算数组的起点和终点.

I am stuck about how to use pointers to display array. I can easily do this with array using for loop but I am interested in knowing how to use via pointers and I am stuck how to calculate starting and ending point of an array.

下面是示例程序

 void printArray(int *ptr);            
{         
    //for statement to print values using array             
    for( ptr!=NULL; ptr++) // i know this doesn't work         
    printf("%d", *ptr);        
}         

int main()    
{    
    int array[6] = {2,4,6,8,10};     
    printArray(array);    
    return 0;     
}

推荐答案

检查NULL技巧仅适用于以NULL结尾的字符串.对于数字数组,您也必须传入大小.

The checking for NULL trick only works for NULL terminated strings. For a numeric array you'll have to pass in the size too.

void printArray(int *ptr, size_t length);            
{         
    //for statement to print values using array             
    size_t i = 0;
    for( ; i < length; ++i )      
    printf("%d", ptr[i]);        
}   

 void printString(const char *ptr);            
{         
    //for statement to print values using array             
    for( ; *ptr!='\0'; ++ptr)        
    printf("%c", *ptr);        
}         

int main()    
{    
    int array[6] = {2,4,6,8,10};     
    const char* str = "Hello World!";
    printArray(array, 6);    
    printString(str);
    return 0;     
}

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

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