#include <stdio.h> #include <stdlib.h> int main(int argc,char ** argv) { char *p; int i; p=malloc(30); strcpy(p,"not 30 bytes"); printf("p=<%s>\n",p); if(argc==2){ if(strcmp(argv[1],"-b")==0) p[50]='a'; else if(strcmp(argv[1],"-f")==0){ free(p); p[0]='b'; } } /*free(p);*/ return 0; }
时间: 2024-01-22 09:03:37 浏览: 18
这是一段 C 语言代码,它包含了一个 main 函数,接受两个参数 argc 和 argv,其中 argc 表示参数的个数,argv 是一个指向参数数组的指针。
该程序首先使用 malloc 函数分配了 30 字节的内存空间,并将其地址赋给指针 p。然后使用 strcpy 函数向该内存空间中写入了一个字符串 "not 30 bytes"。接下来,程序根据命令行参数进行了一些判断:
- 如果命令行参数为 "-b",则向 p 指向的内存空间中的第 50 个字节写入了字母 'a'。
- 如果命令行参数为 "-f",则释放了 p 指向的内存空间,并且向已经被释放的内存空间中的第 0 个字节写入了字母 'b'。
最后,程序返回了 0 表示正常结束。
需要注意的是,程序中注释掉了一行代码 "/*free(p);*/",如果取消注释,程序将会在结束前释放掉 p 指向的内存空间。
相关问题
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { printf("25600"); return 0; }
这段代码是一个简单的C语言程序,它的作用是输出数字25600。在程序中,使用了两个头文件<stdio.h>和<stdlib.h>,其中<stdio.h>包含了输入输出函数,而<stdlib.h>包含了一些常用的函数,例如atof()和atoi()。在main函数中,使用了三个参数,分别是argc、argv[]和return 0。其中,argc表示传递给程序的参数个数,argv[]表示传递给程序的参数列表,而return 0表示程序正常结束。在这个程序中,由于没有使用传递给程序的参数,因此argc和argv[]没有被使用到。
vs2008上,如何使用#include <tar.h> 例子
在 VS2008 中使用 `#include <tar.h>`,需要做以下几个步骤:
1. 下载 tar.h 头文件,可以从网上下载,比如在 GitHub 上可以找到该头文件的代码:https://github.com/panzi/uTAR/blob/master/tar.h
2. 将 tar.h 头文件保存在工程目录下的任意子目录中,比如 `include` 目录。
3. 在 VS2008 中打开工程,右键点击工程名称,选择“属性”,在弹出的对话框中选择“C/C++” -> “常规”,在“附加包含目录”中添加 tar.h 头文件所在目录的路径(比如 `$(ProjectDir)\include`)。
4. 在需要使用 tar.h 头文件的源文件中,加入 `#include <tar.h>` 即可。
例如,下面是一个使用 tar.h 头文件的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tar.h>
int main(int argc, char* argv[])
{
// 创建 tar 文件
struct posix_header header;
memset(&header, 0, sizeof(header));
strncpy(header.name, "test.txt", sizeof(header.name));
strncpy(header.mode, "0000644 ", sizeof(header.mode));
strncpy(header.uid, "0000010 ", sizeof(header.uid));
strncpy(header.gid, "0000010 ", sizeof(header.gid));
strncpy(header.size, "00000000005 ", sizeof(header.size));
strncpy(header.mtime, "00000000000 ", sizeof(header.mtime));
memset(header.chksum, ' ', sizeof(header.chksum));
strncpy(header.typeflag, "0", sizeof(header.typeflag));
strncpy(header.linkname, "", sizeof(header.linkname));
strncpy(header.magic, TMAGIC, sizeof(header.magic));
strncpy(header.version, TVERSION, sizeof(header.version));
strncpy(header.uname, "", sizeof(header.uname));
strncpy(header.gname, "", sizeof(header.gname));
strncpy(header.devmajor, "", sizeof(header.devmajor));
strncpy(header.devminor, "", sizeof(header.devminor));
printf("Header checksum: %s\n", make_checksum(&header));
return 0;
}
```