人力検索はてな
モバイル版を表示しています。PC版はこちら
i-mobile

Cの配列の渡し方について教えて下さい。
下記Perlの例をCで書くとどのようになりますか。
ポインタ扱いで失敗してると思うのですが、どのようにすればいいでしょうか?
また、もし良ければ最もシンプルな書き方を教えて下さい。
宜しくお願い致します。

# Perl
my @ary = (5,4,3,2,1,0);
Test(@ary);
sub Test(){
my @test = @_;
my $aryLen = @test;
my $i;
for ($i =0; $i < $aryLen; $i++){
print "$test[$i]\n";
}
}
// Cではどのようになりますか?
#include <stdio.h>
int ary[] = {5,4,3,2,1,0};
void main(){
Test(ary);
}
Test(int test[]){
int aryLen = sizeof(test) / sizeof(test[0]);
//printf("%d\n", sizeof(test));
//printf("%d\n", sizeof(test[0]));
int i;
for(i = 0; i < aryLen; i++){
printf("%d\n", test[i]);
}
}




# Perlだとかなりシンプルに書けますがCでは?
my @ary = (5,4,3,2,1,0);
Test(@ary);
sub Test(){
for (@_){
print "$_\n";
}
}

●質問者: 匿名質問者
●カテゴリ:コンピュータ 科学・統計資料
○ 状態 :終了
└ 回答数 : 2/2件

▽最新の回答へ

1 ● 匿名回答1号
ベストアンサー

http://wisdom.sakura.ne.jp/programming/c/c46.html
http://www.g-ishihara.com/c_ar_02.htm

#include <stdio.h>
// 配列の要素数を求めるマクロ
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
// mainより後に関数を書くときはプロトタイプ宣言しておきます
void Test(int *test,int testLen);

void main(){
 // グローバル変数にするならTest関数に引数はいりません
 int ary[] = {5,4,3,2,1,0};
 // sizeof 演算子は外部配列のサイズは返せません
 int aryLen = ARRAY_SIZE(ary);
 // 通常は呼ぶ側で渡してあげます
 Test(ary,aryLen);
}

void Test(int *test,int testLen){
 int i;
 
 for(i = 0; i < testLen; i++){
 printf("%d\n", test[i]);
 }
}

匿名質問者さんのコメント
ありがとうございます。 また、細かいコメントありがとうございます。 コードを読み解くのにとても参考になりました。

2 ● 匿名回答3号

cだとシンプルに書けません
cには配列型が無くポインタを使うしかないからです

c++(厳密にはc++11)だとvectorを使えばそれなりにシンプルに書けます

#include <stdio.h>
#include <vector>

void test(std::vector<int>& array) {
 for (auto i: array) 
 printf("%d\n", i);
}

int main() {
 std::vector<int> array {5,4,3,2,1,0};
 test(array);
 return 0;
}

匿名質問者さんのコメント
ありがとうございます。 Cには配列型がないのですか・・・ 今回はArduinoで使う予定だったのですが、コンパイラーを通りませんでしたが、C++を使う際には参考にさせて頂きます!
関連質問

●質問をもっと探す●



0.人力検索はてなトップ
8.このページを友達に紹介
9.このページの先頭へ
対応機種一覧
お問い合わせ
ヘルプ/お知らせ
ログイン
無料ユーザー登録
はてなトップ