简体   繁体   English

阵列分割故障 C

[英]Array Segmentation Fault C

First off, I am not very experienced with C.首先,我对 C 不是很有经验。

I am having to deal with arrays for a problem I need to solve, I have managed to simplify the issue to this:我不得不处理数组来解决我需要解决的问题,我设法将问题简化为:

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

char array[5] = {"hello"}

int main() {

printf(%s\n", array[0]);

return (0);
}

In this case I am just trying to print the 'h', yet I get a Segmentation Fault.在这种情况下,我只是想打印“h”,但出现了分段错误。

You have a number of errors to be fixed,您有许多错误需要修复,

printf(%s\n", array[0]);

Here, you are trying to print a char , try在这里,您正在尝试打印char ,请尝试

printf("%c\n", array[0]);

You are missing a ;你缺少一个;

char array[5] = {"hello"}
                         ^

While declaring a string literal, you don't need the {}在声明字符串文字时,您不需要{}

char array[] = "hello";

First of all lets see what %s does - it expects it corresponding to be an address.首先让我们看看 %s 做了什么 - 它期望它对应于一个地址。 It starts reading from that address byte by byte as if all these bytes were characters and keeps printing them until it finds the null \\0 character.它从该地址开始逐字节读取,就好像所有这些字节都是字符一样,并不断打印它们,直到找到空的\\0字符。

Now, char array[5] = {"hello"} means array[0] is 'h' - that's correct.现在, char array[5] = {"hello"}表示array[0]是 'h' - 这是正确的。 But what's wrong is that you are using %s to print it.但问题是您使用 %s 来打印它。 So, %s considers 'h' to be an address (well to be precise the ascii value of 'h' as the address).所以,%s 认为 'h' 是一个地址(准确地说是 'h' 的 ascii 值作为地址)。 Which is 104 i guess.我猜是 104。 This can be an address alright but cant be accessed by your normal program (too much details here) and hence the segmentation fault这可以是一个地址,但是不能被你的正常程序访问(这里有太多细节),因此是分段错误

So, in short use %c to print characters.所以,简而言之,使用 %c 来打印字符。

Also one thing: array[5] is not enough to hold "hello" - as it is actually 6 characters the sixth is the terminating '\\0' character which is automatically appended to c strings.还有一件事: array[5]不足以容纳“hello”——因为它实际上是 6 个字符,第六个是终止字符 '\\0' ,它会自动附加到 c 字符串。

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

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