#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int i, *x , size ;
char name[100] , *y;
printf("Give name: ");
/* user gives name */
gets(name);
size = strlen(name);
/* gets memory for exactly the name length */
y=(char*)malloc(size*sizeof(char));
for(i=0;i!=' ';i++) {
/* corywrites the name */
*(y+i)=name[i];
}
printf("%s" ,*y);
}
您没有告诉我们您看到了什么问题/症状...但对于初学者来说...
- 测试
name[i] != ' '
而不是i != ' '
- 返回
strlen(name)
长度不包括尾随null
。 - 在
for
循环之后终止 null 终止y
:
所以。。。
y=(char*)malloc((size + 1) * sizeof(char));
for(i=0; name[i] != ' '; i++) {
/* copywrites the name */
y[i] = name[i]; /* changed to array syntax */
}
y[size] = ' ';
printf("%s", y);
如果我手动复制一个字符串,它看起来像:
int i;
for( i = 0; source[i]; i++ ) dest[i] = source[i]; // copy characters
dest[i] = 0; // append null terminator
分配字符串时,需要为空终止符添加 1,复制字符串后,还需要添加空终止符。
您遇到问题,您将i
与初始条件进行比较' '
,它会立即终止。
复制字符串的一种更简单的方法是使用 strcpy 函数。
-
您没有为
y
分配足够的内存。您需要为字符串中的字符数分配空间,并为 null 终止字符再分配一个空格。y = malloc(size + 1);
-
您的循环条件已中断。您可能正在比较字符串中的第 i 个值:
for (i=0; name[i]!=' '; i++) {
-
与其写
*(y+i)
,不如写y[i]
。它更容易理解,并且具有完全相同的语义。for (i=0; name[i]!=' '; i++) { y[i] = name[i]; }
-
您没有将终止
y
为空。y[size] = ' ';
-
打印字符串时,参数应为
char *
类型,而不是char
。所以:printf("%s", y);