2011-08-04 7 views
2

関数パラメータのチェックに何らかの問題があります。 func(char * str)には、3つのタイプの文字列を指定できます。 1. const文字列 2.文字列mallocデータへのポインタ 3. char配列。 c関数が "1111"のようにconst文字列のみを受け入れることを制限することは可能ですか?関数パラメータがchar配列、const文字列、文字列mallocデータへのポインタであることを確認できますか?

私は以下のようなコードを書こうとしていますが、動作しません。

struct test{ 
    const char *val; 
}; 

void func(struct test *t, const char *rodata) 
{ 
    t->val = rodata; 
} 

しかし、私は、私は私が(FUNCに渡すどのrodataチェックすることはできません見つかっ):

/* Test: rodata don't free after function call, it can be the point to*/ 
func(t, "333"); 
printf("%s\n", t->val); 

/* Test: C function can't check rw char array, even with const ...*/ 
char rwdata[] = "22222"; 
func(t, rwdata); 
memset(rwdata, '9', sizeof(rwdata)); 
printf("%s\n", t->val); 

/* Test: C function can't check malloc ?*/ 
char *rwdata2 = strdup("rodata2"); 
free(rwdata); 
func(t, rwdata2); /* cause error */ 
printf("%s\n", t->val); 
} 

答えて

5

ません - すべての3つの引数がポインタです。それらを確実に区別する方法はありません。

0

第三エラー

あなたはこの方法を行うことができ

typedef struct 
{ 
    const char* val; 

}test; 


test func(test t, const char* s) 
{ 
    t.val = s; 
    return t; 
} 


int main() 
{ 
    test t ={0}; 
    char* p = NULL; 

    p= (char*)malloc(4); 

    strncpy(p, "abc", 4); 


    t = func(t, p); 

} 
関連する問題