LoginSignup
0
0

More than 3 years have passed since last update.

関数へのポインタの定義時の注意点

Last updated at Posted at 2020-09-12
ptrToFunc.c
#include <stdio.h>
#include <string.h>

int main(void){
    char *(*ptr_strcpy)(char *,char *) ; //関数へのポインタを定義 (誤)
    char str1[10];
    char str2[] = "hoge";
    ptr_strcpy = strcpy; //ここでエラーになる
    printf( "%s\n", str1);
    return 0;
}

コンパイルしてみると、下記の警告メッセージが出る。

warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
ptr_strcpy = strcpy;

あれ、char*はstrcpy関数の戻り値でしょ 関数へのポインタとなる「ptr_strcpy」の各引数の型もちゃんと定義してるね
調べてみると、実は2番目の引数に
const修飾子があるようだ…

    char *(*ptr_strcpy)(char *, const char *) ; //const修飾子を2番目の引数に追加

問題なくコンパイルできた。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0