一个二维数组赋给int *p问题
#include <stdio.h>void main(){
int numbers[] = {1,2,3,4,5,6,7,8,9,10,11,12};
int *p = numbers;
printf("address for numbers: %p\n", p);
printf("values for numbers:%d\n",*(p+1));
printf("sizeoffor numbers:%d\n",sizeof numbers);
for(int i=0;i < (sizeof(numbers)/sizeof(int));i++){
printf("The values for numbers[%d]:%d\n", i, *(p+i));
}
}
如题, 在cloin下能正常 运行, 但是这个代码有没有问题呢?
比如int *p=numbers这条语句, 赋值有没有问题?两边的类型相同吗?
输出如下:
address for numbers: 0x7ffdefd38400
values for numbers:2
sizeoffor numbers:48
The values for numbers:1
The values for numbers:2
The values for numbers:3
The values for numbers:4
The values for numbers:5
The values for numbers:6
The values for numbers:7
The values for numbers:8
The values for numbers:9
The values for numbers:10
The values for numbers:11
The values for numbers:12
Process finished with exit code 12
你用的教材有点老了,换一个吧
一开始学到的是错误的知识,之后想要改变是非常困难的
#include <stdio.h>
int main(void) {
int numbers[] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}, {11, 12}};
int (*p) = numbers;
printf("address for numbers: %p\n", p);
printf("values for numbers:%p\n",*(p+1));
printf("sizeoffor numbers:%lu\n",sizeof numbers);
for(size_t i=0;i < (sizeof(numbers)/sizeof(int));i++) {
printf("The values for numbers[%lu]:%p\n", i, *(p+i));
}
return 0;
}
你的代码出现下面的问题
main.c:3:6: warning: return type of ‘main’ is not ‘int’ [-Wmain]
3 | void main(){
| ^~~~
main.c: In function ‘main’:
main.c:4:24: warning: missing braces around initializer [-Wmissing-braces]
4 | int numbers[] = {1,2,3,4,5,6,7,8,9,10,11,12};
| ^
| {}{}{}{}{ }{ }
main.c:5:14: warning: initialization of ‘int *’ from incompatible pointer type ‘int (*)’ [-Wincompatible-pointer-types]
5 | int *p = numbers;
| ^~~~~~~
main.c:8:34: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
8 | printf("sizeoffor numbers:%d\n",sizeof numbers);
| ~^ ~~~~~~~~~~~~~~
| | |
| intlong unsigned int
| %ld
人造人 发表于 2021-4-20 14:29
你的代码出现下面的问题
怎么我编译器没报错呢, 奇怪了 喜欢散步 发表于 2021-4-20 14:37
怎么我编译器没报错呢, 奇怪了
我用的gcc,编译命令是 gcc -g -Wall -o main main.c
页:
[1]