我正在学习c中的字符串.我使用code :: blocks作为编译器,即使它不仅仅用于c.因此,下面代码的问题是string2的输出是存储的5个字符加上string1的输出.我会给你看:
#include <stdio.h>
#include <string.h> /* make strncpy() available */
int main()
{
char string1[]= "To be or not to be?";
char string2[6];
/* copy first 5 characters in string1 to string2 */
strncpy (string2, string1, 5);
printf("1st string: %s\n", string1);
printf("2nd string: %s\n", string2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
1st string contains: To be or not to be?
2nd string contains: To be To be or not to be?
Run Code Online (Sandbox Code Playgroud)
如果你问我,那超过5个字符......
我正在接近Mike McGrath撰写的关于c编程的介绍性书籍的结尾,该书称为"简单的C编程".我想我会在本书之后通过外观来了解更多内容.无论如何,我正在使用内存分配,我编写了这个演示程序,但是当我尝试运行它时错误已关闭:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, *arr;
arr = calloc(5, sizeof(int));
if(arr!=NULL)
{
printf("Enter 5 integers, seperated by a space:");
for(i=0; i<5; i++) scanf("%d", &arr[i]);
printf("Adding more space...\n");
arr = realloc(8, sizeof(int));
printf("Enter 3 more integers seperated by a space:");
for(i=5; i<8; i++) scanf("%d", &arr[i]);
printf("Thanks.\nYour 8 entries were: ");
for(i=0; i<8; i++) printf("%d, ", arr[i]);
printf("\n");
free(arr);
return 0;
}
else {printf("!!! INSUFFICIENT MEMORY !!!\n"); return 1; }
}
Run Code Online (Sandbox Code Playgroud)
警告信息:
|13|warning: passing argument 1 …
Run Code Online (Sandbox Code Playgroud)