chuchienshu
chuchienshu

Reputation: 45

Output different value after function call?

I'm confusing about the different sizeof() return value after function check() calls. And buf exactly the same as buffer based on the printf() for each char. Any reply is awesome! Thx.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void check(char *buf)
{

    printf("%d \n", sizeof(buf)); // **output 8**

}
int main(int argc, char *argv[])
{

    char buffer[] = "\x64\x49\x00\x55\x33\x33\x33\x64\x49\x00\x00\x00\x55\x33\x33\x33\x64\x49\x00\x00\x00\x55\x33\x33\x64\x49\x00\x00\x00\x55\x33\x33";
    printf("%d\n", sizeof(buffer)); // **output 33**
    check(buffer);

}

Upvotes: 0

Views: 29

Answers (1)

0___________
0___________

Reputation: 67476

In function check buffer is a pointer to the char and its size is 8

In the main furnctions buffers is the 33 elements char array and its size is 33

To get the length of the C string use strlen function.

Generally there is no way of getting the size of the array referenced by the pointer. You need to pass the size as a anothother parameter.

In your example:

void check(char *buf, size_t size)
{

    printf("%zu \n", size);

}
int main(int argc, char *argv[])
{

    char buffer[] = "\x64\x49\x00\x55\x33\x33\x33\x64\x49\x00\x00\x00\x55\x33\x33\x33\x64\x49\x00\x00\x00\x55\x33\x33\x64\x49\x00\x00\x00\x55\x33\x33";
    printf("%d\n", sizeof(buffer)); // **output 33**
    check(buffer, sizeof(buffer));

}

Upvotes: 1

Related Questions