word2vec用到的c语言知识

argc,avgv用法

argc 表示有几个参数,因为至少要指定一个应用程序的名,所以argc>=1. argv表示参数是什么。

int main(int argc, char **argv) {
    printf("hello world.
");
    printf("argc=%d
", argc);
    int i = 0;
    for (i = 0; i < argc; i++) {
        printf("%s
", argv[i]);
    }
    return 0;
}

判断命令行输入有没有某个字符串.

如果没有返回-1,如果有把字符串后面的数字转化为整型.

int ArgPos(char *str, int argc, char **argv) {
    int a;
    for (a = 1; a < argc; a++) {
        if (!strcmp(str, argv[a])) {
            if (a == argc - 1) {
                printf("Argument missing for %s
", str);
                exit(1);
            }
            return a;
        }
    }
    return -1;
}

int main(int argc, char **argv) {
    int i;
    if ((i = ArgPos((char *)"-size", argc, argv)) > 0) {
        printf("argv=%d", atoi(argv[i + 1]));
    }
    return 0;
}

alloc

malloc和alloc的作用类似,申请连续的内存空间.不同是calloc申请空间的内容被清空.malloc申请空间的内容是随机的.

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
struct student {
    int id;
    int score;
};
struct student* s1;
struct student* s2;
/*
 * malloc和alloc的作用类似,申请连续的内存空间.不同是calloc申请空间的内容被清空.
 * malloc申请空间的内容是随机的.
 */
int main(int argc, char **argv) {
    s1 = (struct student*)calloc(MAX, sizeof(struct student));
    printf("%d, %d
", s1[0].id, s1[0].score);

    s2 = (struct student*)malloc(MAX * sizeof(struct student));
    printf("%d, %d
", s2[0].id, s2[0].score);
    return 0;
}

fscanf

把文件中的内容读取到内存

#include <stdio.h>
#include <stdlib.h>
int main(){
    char str1[10], str2[10], str3[10];
    int year;
    FILE * fp;
    fp = fopen ("file.txt", "w+");
    fputs("We are in 2012", fp);
    rewind(fp);//重新指向流的开头
    fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);//把数据从文件中读到内存
    printf("Read String1 |%s|
", str1 );
    printf("Read String2 |%s|
", str2 );
    printf("Read String3 |%s|
", str3 );
    printf("Read Integer |%d|
", year );
    fclose(fp);
    return(0);
}

posix_memalign

linux支持posix_memalign,windows不支持.posix_memalign申请空间考虑了内存对齐的问题.和malloc,calloc相比效率更高.第一个参数要转化成(void**),第2个参数必须是2^n,第3个参数必须是第2个参数的倍数.最终申请的空间数是第3个参数指定的,申请空间的类型是*buf.

#include <stdio.h>
#include <stdlib.h>
int main() {
    float *buf;
    int ret;
    ret = posix_memalign((void**)&buf, 256, sizeof(float) * 256);
    if (ret) {
        printf ("error.");
        return -1;
    }
    int i;
    for (i = 0; i < 256; i++) {
        buf[i] = i;
    }
    for (i = 0; i < 256; i++) {
        printf("%f
", buf[i]);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zhouyang209117/p/7218835.html