c - string 和 malloc...出了什么问题?

标签 c string malloc

#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/

相关文章:

c - 以二的幂分配内存更好吗?

C++ malloc - 动态数组

c - 在函数之间传递结构

c - C下实现多线程应用程序

使用 sscanf 将字符串转换为时间

c - Valgrind,有可能得到行数吗?

c# - 从 C# 中的两个字符串变量转换为 DateTime

php - 去除字符串中的非数字字符

C++函数性能问题

c - 我遇到了段错误,但我没有找到 oO?