前提・実現したいこと
C言語初心者です。
ポインタと再帰の勉強のため、配列ポインタを引数として受け取り、同名の配列を関数内で定義して引数の配列をコピーしてその配列の先頭のポインタを表示した後再びその関数を呼び出すvoid operator()関数を作成しました(コード1)。引数の配列ポインタ名と同名の配列を関数内で再定義していますが、プログラムはエラーなく動作して配列のポインタを返します(結果1)。
しかしこのコードを改変して、配列ポインタを引数として受け取り関数内で同名の配列を定義してポインタを返すコード(コード2)を実行すると
redefinition of 'result' with a different type: 'int [20]' vs 'int *' int result[20];
とエラーがでます。引数名と同じ変数名を同じ関数内で定義しているのでエラーがでるのは納得できるのですが、なぜコード1はエラーを返さず動作するのでしょうか?
(コード1)
#include <stdio.h>
void operator(int result[],int n)
{
if(n>0){
int result[5];
for(int i=0;i<5;i++) result[i]=result[i];
printf("result:%p\n",result);
n--;
operator(result,n);
}
}
int main(void){
int result[5];
int i;
for(i=0;i<5;i++){result[i]=0;}
operator(result,10);
return 0;
}
(結果1)
result:0x7ffdd0abb830
result:0x7ffdd0abb800
result:0x7ffdd0abb7d0
result:0x7ffdd0abb7a0
result:0x7ffdd0abb770
result:0x7ffdd0abb740
result:0x7ffdd0abb710
result:0x7ffdd0abb6e0
result:0x7ffdd0abb6b0
result:0x7ffdd0abb680
(コード2)
#include <stdio.h>
void operator(int result[])
{
int result[5]; for(int i=0;i<5;i++) result[i]=result[i]; printf("result:%p\n",result);
}
int main(void){
int result[5];
int i;
for(i=0;i<5;i++){result[i]=0;}
operator(result);
return 0;
}
(コード2に対するエラーメッセージ)
Main.c:6:9: error: redefinition of 'result' with a different type: 'int [5]' vs 'int *'
int result[5];
^
Main.c:3:19: note: previous definition is here
void operator(int result[])
^
1 error generated.
実行環境はpaiza ioというオンライン実行環境です。
よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー