为什么在printf()而不是数组中使用*指针不起作用? [英] Why doesn't it work to use *pointer in printf() rather than array?

查看:80
本文介绍了为什么在printf()而不是数组中使用*指针不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个教程中被告知我可以在printf here函数中使用*指针而不是数组,因为它们本质上是一样的。



但是当我运行时它与*指针程序崩溃,为什么这不起作用?谢谢!



https://s12.postimg.org/uls819rul/C_question.png [ ^ ]



我尝试过:



我尝试使用*指针作为打印在printf函数中的内容然后崩溃...但是数组工作。

I was told in a tutorial I could use *pointer in the printf here function instead of array because they are essentially the same thing.

However when I run it with *pointer the program crashes, why doesn't this work? Thanks!

https://s12.postimg.org/uls819rul/C_question.png[^]

What I have tried:

I've tried using the *pointer as what to print in the printf function and it crashes... however array works.

推荐答案

我刚试过它有一点点改进:

I just tried it with a small improvement:
#include <stdio.h>

int main()
{
    char array[] = "Eoin Kenny\0";
    char *p = array;
    *p = 'O';
    p++;
    *p = 'w';
    p++;
    *p = 'e';
    p++;
    *p = 'n';
    p++;
    printf("My array is: %s", array);

    return 0;
}

它有效:

And it works:

My array is: Owen Kenny

唯一的真实更改是添加一个字符串终止符,以便printf不会在字符串的末尾运行。

可能是缺少的null是让你认为它崩溃的原因!

但我要做的事情稍微简单一些:

The only "real" change is the addition of a string terminator so that the printf doesn't run off the end of the string.
It may be that the missing null is what makes you think it's crashed!
But what I'd do is slightly simpler:

#include <stdio.h>

int main()
{
    char array[] = "Eoin Kenny\0";
    char *p = array;
    *p++ = 'O';
    *p++ = 'w';
    *p++ = 'e';
    *p++ = 'n';
    printf("My array is: %s", array);

    return 0;
}





BTW:将来不发布你的代码图片:复制并粘贴它以便我们可以运行它就像你输入它一样。



BTW: In future doesn't post images of your code: copy and paste it so we can run it here exactly as you typed it.


这篇关于为什么在printf()而不是数组中使用*指针不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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