在C语言中为指针分配字符串 [英] Assigning strings to pointer in C Language

查看:173
本文介绍了在C语言中为指针分配字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言的新手,我的问题是关于指针的.据我了解和搜索的指针,只能存储其他变量的地址,而不能存储实际值(如整数或字符).但是在下面的代码中,char指针c实际上存储了一个字符串.它执行无误,并将输出命名为'name'.

I am a new learner of C language, my question is about pointers. As far I learned and searched pointers can only store addresses of other variables, but cannot store the actual values(like integers or characters). But in the code below the char pointer c actually storing a string. It executes without errors and give the output as 'name'.

#include <stdio.h>
main()
{
    char *c;
    c="name";
    puts(c);
}

谁能解释一个指针如何在没有任何内存的情况下存储字符串,或者是否在创建该内存的位置创建了内存以及可以创建多少大小.

can anyone explain how a pointer is storing a string without any memory or if memory is created where it is created and how much size it can be created.

我尝试将其与整数类型指针一起使用

I tried using it with the integer type pointer

#include <stdio.h>
main()
{
    int *c;
    c=10;
    printf("%d",c);
}

但是它给出了一个错误

cc     test.c   -o test
test.c: In function ‘main’:
test.c:5:3: warning: assignment makes pointer from integer without a cast   [enabled by default]
c=10;
^
test.c:6:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("%d",c);
^

指针存储变量的地址,然后为什么整数指针与字符指针不同?

Pointers stores the address of variable then why is integer pointer different from character pointer.

如果我缺少有关指针plz解释的内容.

If there is something I am missing about pointers plz explain.

推荐答案

  1. char *c; c="name";

  1. char *c; c="name";

如果您在此处观察到,则不是在给变量c分配字符串名称",而是在将name存储到变量c的内存的基址分配.

If you observe here, you are not assigning string "name" to variable c but, you are assigning the base address of memory where name is stored into variable c.

字符串name存储在编译器创建的字符串表中,这种形式的所有字符串都存储在字符串表中,该字符串表是const类型,这意味着您无法再次写入该位置.例如,您可以尝试这两行char *p = "Hello" ; strcpy(p,"Hi");.编译时,第二行会出现错误.

The string name is stored in the string table created by the compiler, all the strings of this form are stored in string table, this string table is a const type, meaning you cannot write again to this location. e.g you can try these two lines char *p = "Hello" ; strcpy(p,"Hi");. While compilation you will get error at second line.

int *c; c = 10;

int *c; c = 10;

在上面的代码中,您正在创建一个整数指针并为其分配10,这里的编译器了解到您正在将10分配为地址.您需要了解的另一件事是所有指针变量仅存储无符号整数常量.因此,即使在这两种情况下均为char *cint *c,变量c都仅存储无符号整数.

In the above code you are creating an integer pointer and assigning 10 to it, the compiler here understands that you are assigning 10 as an address. One more thing you need to understand is all the pointer variables store unsigned interger constants only. So even if it is char *c or int *c in both of these cases the variable c stores an unsigned integer only.

这篇关于在C语言中为指针分配字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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