简体   繁体   English

C Char指针

[英]C Char pointers

Let us say we have a array of pointers: 让我们说我们有一系列指针:

char *ptr[30];

Now this works fine, and doesn't seems to do anything unexpected! 现在这个工作正常,似乎没有做任何意想不到的事情! I can input names easily. 我可以轻松输入名字。

scanf("%s", ptr[1]);
scanf("%s", ptr[2]);
scanf("%s", ptr[3]);

printf("%s\n", ptr[1]);
printf("%s\n", ptr[2]);
printf("%s\n", ptr[3]);

My question is if a pointer can be used in this way to store end number of names, then why is malloc used.? 我的问题是,如果一个指针可以用这种方式来存储名称的结尾数,那么为什么要使用malloc呢? and in this case ptr[1] does not point to the character in the input but to a new input itself. 在这种情况下,ptr [1]不指向输入中的字符,而是指向新输入本身。 for eg if ptr has mukul, ptr[1] should point to 'u' and if space is not allocated when a pointer is declared like this, what are the limits.? 例如,如果ptr有mukul,ptr [1]应该指向'u',如果在指定这样的指针时没有分配空间,那么限制是多少?

The pointer cannot be used that way. 指针不能以这种方式使用。 It might "work" for you sometimes by sheer chance, but using a pointer without allocating memory for it will cause undefined behavior - meaning that your program may behave erratically and give you unexpected results. 它有时可能通过纯粹的机会“起作用”,但使用指针而不为其分配内存将导致未定义的行为 - 这意味着您的程序可能表现不正常并给您意想不到的结果。

Remember, just because your program compiles and runs doesn't mean it is correct. 请记住,仅仅因为您的程序编译和运行并不意味着它是正确的。 In the C language there is a whole class of errors known as "undefined behavior", many of which the compiler will happily let you do without complaining. 在C语言中,存在一类称为“未定义行为”的错误,其中许多编译器很乐意让您无需抱怨。 These include overwriting a buffer, using an uninitialized variable, or dereferencing a pointer that doesn't point to a legitimately allocated memory block. 这些包括使用未初始化的变量覆盖缓冲区,或者取消引用不指向合法分配的内存块的指针。 Programs that exhibit undefined behavior may even appear to work normally sometimes - but they are usually very unstable and prone to crash. 显示未定义行为的程序有时甚至可能正常工作 - 但它们通常非常不稳定并且容易崩溃。

If you use what is in your example, you just owerwrite other locations what come after your ptr array. 如果你使用你的例子中的内容,你只需要在你的ptr数组之后写下其他位置。 Most compilers should actually give at least a warning. 大多数编译器实际上应该至少给出一个警告。 Your program would crash on most systems, you were just very lucky. 您的程序会在大多数系统上崩溃,您只是非常幸运。

When you define a pointer like: 定义指针时:

char *ptr = 0; // NULL pointer: dereferencing it will crash
puts(ptr);    // crash

You merely create a link to a place in memory: 您只需创建一个指向内存中某个位置的链接:

ptr = "string"; // dereferencing it will show the string
puts(ptr);     // displaying "string"

So having an array of pointers merely creates a list of references to other variables. 因此,拥有一个指针数组只会创建一个对其他变量的引用列表。

To reference a place in memory, you then have to assign variables to your pointers, or allocate memory for each pointer. 要引用在内存中的地方,你必须变量分配给您的指针,或者每个指针分配内存。

You've allocated space for 30 pointers, but you haven't initialized them to point anywhere meaningful. 你已经为30个指针分配了空间,但你没有初始化它们指向任何有意义的地方。 Unless you declared the array outside of a function, each element in the array will contain some random bit string that may or may not correspond to a writable memory location. 除非您在函数外部声明了数组,否则数组中的每个元素都将包含一些随机位字符串,该字符串可能与可写内存位置相对应,也可能不相对应。 If we drew a picture, it would look something like this (all addresses are pulled out of thin air; don't assume this corresponds to any real architecture): 如果我们绘制一张图片,它看起来就像这样(所有地址都是凭空而来的;不要假设这对应于任何真实的架构):

Item       Address       0x00  0x01  0x02  0x03
----       -------       ----  ----  ----  ----
ptr        0xbbc81230    0x??  0x??  0x??  0x??
           0xbbc81234    0x??  0x??  0x??  0x??
           0xbbc81238    0x??  0x??  0x??  0x??
           ...
           0xbbc812a8    0x??  0x??  0x??  0x??

where 0x?? 其中0x?? represents a random byte value. 表示随机字节值。 For the behavior you've described, each of the random values just happens to point to writable memory, and writing over whatever's stored there just happens to not have any immediate ill effects. 对于你所描述的行为,每个随机值恰好指向可写内存,并且写入存储在那里的任何内容恰好没有任何直接的不良影响。

Bad juju: it looks like your code is working properly when in reality it's behaving very badly, and can lead to some nasty runtime problems elsewhere in your program that's a pain to debug. 坏juju: 看起来你的代码工作正常,但实际上它的表现非常糟糕,并且可能导致程序中其他地方出现一些令人讨厌的运行时问题,这是一个很难调试的问题。

You will need to explicitly set each element of the ptr array to point to a valid memory location before attempting to write through it. 在尝试写入之前,您需要显式设置ptr数组的每个元素以指向有效的内存位置。

Suppose we add the following code: 假设我们添加以下代码:

ptr[0] = malloc(strlen("foo") + 1);
strcpy(ptr[0], "foo");
ptr[1] = malloc(strlen("bar") + 1);
strcpy(ptr[1], "bar");

We've dynamically allocated some extra memory to hold a couple of strings, and stored the pointers to those new buffers to ptr[0] and ptr[1] . 我们动态分配了一些额外的内存来保存几个字符串,并将指针存储到ptr[0]ptr[1]新缓冲区。

Our picture would now look something like this: 我们的图片现在看起来像这样:

Item       Address       0x00  0x01  0x02  0x03
----       -------       ----  ----  ----  ----
           0x80ff0000     'f'   'o'   'o'  0x00
           ...
           0x80ffcdc0     'b'   'a'   'r'  0x00
           ...
ptr        0xbbc81230    0x80  0xff  0x00  0x00
           0xbbc81234    0x80  0xff  0xcd  0xc0
           0xbbc81238    0x??  0x??  0x??  0x??
           ...
           0xbbc812a8    0x??  0x??  0x??  0x??

ptr[0] now contains the address of a buffer sized to hold 4 char values, and we copy the string "foo" to that buffer. ptr[0]现在包含一个缓冲区的地址,其大小可以容纳4个char值,我们将字符串“foo”复制到该缓冲区。 Similarly, ptr[1] contains the address of another 4-byte buffer that now contains the string "bar". 类似地, ptr[1]包含另一个4字节缓冲区的地址,该缓冲区现在包含字符串“bar”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM