如何用write()输出字符串指定索引字符?解决参数类型警告问题
write() Warning and Output Issue Let's break down why your code is throwing that warning and failing to produce output, then fix it step by step.
The Root Problem
The write() system call expects its second argument to be a pointer to the data you want to write (const void*), but you’re passing name[strlen(name)-1]—which is a single char value (the ASCII code for '3', which is 51). When you pass an integer where a pointer is required, the compiler treats that integer as a memory address. So write() tries to read 1 byte from address 0x33 (hex for 51), which is invalid memory—hence no output and the "pointer from integer without a cast" warning.
The Simple Fix: Pass the Character's Address
Instead of passing the character itself, pass its memory address using the & (address-of) operator. This gives write() the valid pointer it needs:
#include <unistd.h> #include <string.h> int main() { char name[] = "Name123"; size_t str_length = strlen(name); // Add a safety check to avoid index underflow if the string is empty if (str_length > 0) { // Pass the address of the last character write(2, &name[str_length - 1], 1); } return 0; }
What’s Different Here?
&name[str_length - 1]returns a pointer directly to the '3' character in the array, which matches theconst void*typewrite()expects.- We added a check for
str_length > 0becausestrlen()returns asize_t(unsigned integer). If the string were empty,str_length - 1would wrap around to a huge value, causing an out-of-bounds access.
Why This Works
When you run this corrected code, write() reads 1 byte from the valid address of the '3' character and writes it to file descriptor 2 (stderr, which prints directly to your terminal). You’ll see the desired '3' output as expected.
内容的提问来源于stack exchange,提问作者Junaid

