在main里面sizeof(s1)-sizeof(s2)=2,但是在自己写的函数里却等于0;
在main里面sizeof(s1)-sizeof(s2)=2,但是在自己写的函数里却等于0;#include<stdio.h>
int my_strcmp(char s1[], char s2[]);
int main()
{
char s1[] = "hello world";
char s2[] = "hello abc";
printf("%d %d\n",sizeof(s1),sizeof(s2));
int flag = my_strcmp(s1, s2);
printf("%d\n", flag);
printf("%d\n", sizeof(s1)-sizeof(s2));
if(flag == 0)
{
printf("%s 等于 %s\n", s1, s2);
}
else if(flag > 0)
{
printf("%s 大于 %s\n", s1, s2);
}
else
{
printf("%s 小于 %s\n", s1, s2);
}
return 0;
}
#include<stdio.h>
int my_strcmp(char s1[], char s2[])
{
int c;
c= sizeof(s1)-sizeof(s2);
printf("%d\n", sizeof(s1)-sizeof(s2));
printf("%d\n",c);
// return sizeof(s1)-sizeof(s2);
return c;
}
打印结果为:
12 10
0
0
0
2
hello world 等于 hello abc
--------------------------------
这里不懂其原因,感谢帮助! 数组作为参数传递给其他函数以后就不是数组了,变成指针了
$ cat main.c
#include <stdio.h>
int a;
void func(int b) {
int c;
printf("sizeof(b) == %lu\n", sizeof(b));
printf("sizeof(a) == %lu\n", sizeof(a));
printf("sizeof(c) == %lu\n", sizeof(c));
}
int main(void) {
int d;
int e;
func(d);
printf("sizeof(a) == %lu\n", sizeof(a));
printf("sizeof(d) == %lu\n", sizeof(d));
printf("sizeof(e) == %lu\n", sizeof(e));
return 0;
}
$ gcc -g -Wall -o main main.c
main.c: In function ‘func’:
main.c:7:40: warning: ‘sizeof’ on array function parameter ‘b’ will return size of ‘int *’ [-Wsizeof-array-argument]
7 | printf("sizeof(b) == %lu\n", sizeof(b));
| ^
main.c:5:15: note: declared here
5 | void func(int b) {
| ~~~~^~~~~
$ ./main
sizeof(b) == 8
sizeof(a) == 40
sizeof(c) == 120
sizeof(a) == 40
sizeof(d) == 80
sizeof(e) == 160
$ 人造人 发表于 2022-1-10 11:46
数组作为参数传递给其他函数以后就不是数组了,变成指针了
好吧,感谢 #include <stdio.h>
int check(const char *A, const char *B){
for(int i = 0; *(A+i) || *(B+i); i++) if(*(A+i) - *(B+i) != 0) return *(A+i) - *(B+i);
return 0;
}
int main(){
char *str1 = "hello world";
char *str2 = "hello abc";
printf(check(str1, str2) > 0 ? "%s > %s" : check(str1, str2) < 0 ? "%s < %s" : "%s == %s", str1, str2);
return 0;
}
页:
[1]