在简单程序中复制到指针时,C strcpy无法正常工作吗? [英] C strcpy does not work when copying to a pointer in a simple program?

查看:206
本文介绍了在简单程序中复制到指针时,C strcpy无法正常工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#include <string.h>

int main(void) {
    char *w;
    strcpy(w, "Hello Word");
    printf("%s\n", w);
    return 0;
}

以上代码中使用char指针的方式有什么问题?

What is wrong with the way the char pointer is used in the above code?

推荐答案

好吧,您没有要求系统提供内存,而是将其与字符串一起使用.该代码将起作用

Ok, you did not ask to the system for memory, to use it with the string. This code will work

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
   char w[11];
   strcpy(w, "Hello Word");
   printf("%s\n", w);
   return 0;
}

该代码将w声明为char数组,为其保留存储空间.另一种选择是将malloc或calloc用作char指针.阅读有关此内容.

That code declare w as an array of char, reserving the memory space for it. Other alternative is to use malloc or calloc for the char pointer. Read about that.

这篇关于在简单程序中复制到指针时,C strcpy无法正常工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆