欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > 指针数组和数组指针作为函数参数使用

指针数组和数组指针作为函数参数使用

2024/10/24 21:23:03 来源:https://blog.csdn.net/weixin_29898767/article/details/139600484  浏览:    关键词:指针数组和数组指针作为函数参数使用

1. 区分:根据优先级   [] > *

指针数组与数组指针
区分指针数组与数组指针的方法,还是得看优先级()>[ ]>*,
(*p)[n]:根据优先级,先看括号内,则p是一个指针,这个指针指向一个一维数组,数组长度为n,这是“数组的指针”,数组指针就是指向数组的指针;
*p[n]:根据优先级,先看[],则p是一个数组,再结合 *,这个数组的元素是指针类型,共n个元素,这是“指针的数组”,指针数组是存放指针的数组。

2.   指针数组作为函数参数  :  优先级  [] > *

void print_strings(const char *strings[], int count) {  
    for (int i = 0; i < count; i++) {  
        printf("%s\n", strings[i]);  
    }  
}  

int main() {  
    const char *my_strings[] = {"Hello", "World", "!"};  
    print_strings(my_strings, 3);  
    return 0;  
}

2. 数组指针作为函数参数

void print_matrix(const char *matrix[], int rows, int cols) {  
    for (int i = 0; i < rows; i++) {  
        for (int j = 0; j < cols; j++) {  
            printf("%c ", matrix[i][j]);  
        }  
        printf("\n");  
    }  
}  


int main() {  
    const char *matrix[] = {  
        "Hello",  
        "World",  
        "Foo"  
    }; // 注意这不是真正的二维字符数组,而是字符串数组(即字符指针数组)  
    print_matrix(matrix, 3, /* 这里需要假设每行长度相同或提供其他方式来知道列数 */);  
    return 0;  
}

3. 

总结:指针数组和数组指针都可以用做函数参数。但是

当用 二维字符数组或者说是字符串数组 作为函数参数时,建议使用 数组指针。

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

void print(const char (*ptr)[16],int size)  // or void print(const char ptr[][16],int size)
{
    for ( int i=0; i< size; i++)
      printf("ptr[%d] =%s \n",i,ptr[i]);

}

 
int main() 
{  

   const char str[4][16]={"orderId",  "srcCode","dstCode","podCode"};  
   print(str,4);
   return 0;  
}

错误示范:

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

void print_strings( char *strings[], int count) {  

        strcpy(strings[0],"good");

}  

int main() {  
     char my_strings[10][20] = {"Hello", "World", "!"};  
    print_strings(my_strings, 3);  

    printf("%s \n",my_strings[0]);
    return 0;  
}

报错:test.c:8:6: note: expected ‘char **’ but argument is of type ‘char (*)[20]’
 void print_strings( char *strings[], int count) { 

但是下面是可以的

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

void print_strings( char *strings[], int count) {  

           printf("%s \n",strings[0]);

}  

int main() {  
     char *my_strings[] = {"Hello", "World", "!"};  
    print_strings(my_strings, 3);  

 
    return 0;  
}
本质: char *my_strings[] 是一个 char **  ; char my_strings[10][20] 是一个字符数组,所以用数组指针是最好

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com