开发者

pointer to a char pointer and arrya of char pointers

开发者 https://www.devze.com 2023-01-17 00:44 出处:网络
is there any difference between an array of char pointers an开发者_运维知识库d a pointer to a char pointer?http://c-faq.com/aryptr/aryptr2.html

is there any difference between an array of char pointers an开发者_运维知识库d a pointer to a char pointer?


http://c-faq.com/aryptr/aryptr2.html

It's not the same, since it compares a char array to a pointer to a char, but the principle is the same -- just replace the letters in the illustration with pointers.


Yes, there are differences between an array of things and a pointer to a thing, but they usually disappear under certain circumstances.

When you pass an array to a function (for example), that degrades to a pointer to the first element in that array.

An example:

#include <stdio.h>

static void func (char arr[], char *parr) {
    printf ("in func: %3d %3d\n", sizeof(arr), sizeof (parr));
}
int main (void) {
    char arr[100], *parr = arr;
    printf ("         arr ptr\n");
    printf ("         --- ---\n");
    printf ("in main: %3d %3d\n", sizeof(arr), sizeof (parr));
    func (arr, parr);
    return 0;
}

This outputs:

         arr ptr
         --- ---
in main: 100   4
in func:   4   4

This usually annoys people no end since you can't get the size of an "array" passed to a function (you only get the size of what was passed, which is a pointer). If you want the actual size, you have to pass it along as well:

int array[100];
doSomethingWith (array, sizeof (array));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号