标签: c

  • C语言关于函数指针的&和*

    C89,调用函数指针,需要在函数指针前加*,对函数指针赋值,需要在函数名前面加&

    C89,以后,对函数指针操作不需要& 和 *,但,使用它们是个好习惯

    如下代码(C89函数指针风格)

    #include <stdio.h>
    #include <stdlib.h>
    int max(int x, int y)
    {
        return (x > y ? x :y);
    }
    int main ( int argc, char *argv[] )
    {
        int (*p)(int,int) = &max;	// 这里&max
        int a, b, c;
        scanf("%d%d", &a, &b);
        c = (*p)(a,b);	// 这里(*p)
        printf("%d\n", c);
        return EXIT_SUCCESS;
    } 

  • C语言拆分字符串strtok

    C语言拆分字符串strtok函数

    Example
    /* STRTOK.C: In this program, a loop uses strtok
     * to print all the tokens (separated by commas
     * or blanks) in the string named "string".
     */
    #include <string.h>
    #include <stdio.h>
    char string[] = "A string/tof ,,tokens/nand some  more tokens";
    char seps[]   = " ,/t/n";
    char *token;
    void main( void )
    {
       printf( "%s/n/nTokens:/n", string );
       /* Establish string and get the first token: */
       token = strtok( string, seps );
       while( token != NULL )
       {
          /* While there are tokens in "string" */
          printf( " %s/n", token );
          /* Get next token: */
          token = strtok( NULL, seps );
       }
    }
  • C语言十进制转二进制(移位法)

    C语言十进制转二进制(移位法)

    #include <stdio.h>
    int main()
    {
    	char strBinary[sizeof(int)*8+1];
    	int a = 100;
    	// 让p指向strBinary的最后一位
    	char *p = strBinary + sizeof(int)*8;
    	*p = '/0';
    	while (a)
    	{
    		--p;
    		*p = (a & 1) + 0x30;	// 加0x30转变成字符
    		a >>= 1;	// 右移一位
    	}
    	printf("%s/n", p);
    	return 0;
    }
  • 温故而知新,函数指针

     函数指针:

    一个函数在编译时被分配一个入口地址,这个入口地址就是函数指针.可以用一个指针变量指向该函数指针,然后通过该变量来调用函数.

    声明:

    返回值类型 (*指针变量名)(参数类型列表);

    typedef 返回值类型 (*指针变量名)(参数列表名);