#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!='\0';i++) {
/* corywrites the name */
*(y+i)=name[i];
}
printf("%s" ,*y);
}
最佳答案
您没有告诉我们您遇到了什么问题/症状...但首先...
- 测试
name[i] != '\0'
而不是i != '\0'
strlen(name)
返回的长度不包括尾随null
。- 在
for
循环之后以 null 终止y
:
所以...
y=(char*)malloc((size + 1) * sizeof(char));
for(i=0; name[i] != '\0'; i++) {
/* copywrites the name */
y[i] = name[i]; /* changed to array syntax */
}
y[size] = '\0';
printf("%s", y);
关于c - string 和 malloc...出了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27027731/