The following piece of code should Answer to your Question:
#include <stdio.h>
#include <string.h>
void foo(char *msg){
printf("\n");
printf("Sizeof MSG = %zu\n", sizeof(msg));
printf("Length of MSG = %zu\n", strlen(msg));
}
int main(void) {
char msg[10] = "Michi";
printf("Sizeof MSG = %zu\n", sizeof(msg));
printf("Length of MSG = %zu\n", strlen(msg));
foo(msg);
return 0;
}
Output:
Sizeof MSG = 10
Length of MSG = 5
Sizeof MSG = 8
Length of MSG = 5
Why is Sizeof MSG = 10
inside main
? Because you print the size of the Array.
Why is Sizeof MSG = 8
inside foo
? Because you print the size of the Pointer, which on your machine (like mine) happens to be 8
.
Arrays decays to pointer to its first element, when are used as Function arguments.
In other words, things like this:
#include <stdio.h>
#include <string.h>
void foo(int *msg){
printf("\n");
printf("Sizeof MSG = %zu\n", sizeof(msg));
printf("Length of MSG = %zu\n", strlen(msg));
}
int main(void) {
int msg[10] = {1,2,3,4,5};
printf("Sizeof MSG = %zu\n", sizeof(msg));
printf("Length of MSG = %zu\n", strlen(msg));
foo(msg);
return 0;
}
Will not work and probably your compiler will warn you about that:
error: passing argument 1 of ‘strlen’ from incompatible pointer type
Because strlen
is defined like this:
size_t strlen(const char *str)
As you can see strlen
need a char*
and not an int*
.
To fix it you need to pass the length too, like this:
#include <stdio.h>
#include <string.h>
void foo(int *msg, size_t length){
size_t i=0;
printf("\n\n");
printf("Sizeof MSG = %zu\n",length);
for (i = 0; i<length;i++){
printf("%d ",msg[i]);
}
}
int main(void) {
int msg[] = {1,2,3,4,5,6,7,8,9,10};
size_t length = sizeof msg / sizeof msg[0];
size_t i=0;
printf("\n");
printf("Sizeof MSG = %zu\n",length);
for (i = 0; i<length;i++){
printf("%d ",msg[i]);
}
foo(msg, length);
return 0;
}
Output:
Sizeof MSG = 10
1 2 3 4 5 6 7 8 9 10
Sizeof MSG = 10
1 2 3 4 5 6 7 8 9 10