You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用write()输出字符串指定索引字符?解决参数类型警告问题

Fixing the 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 the const void* type write() expects.
  • We added a check for str_length > 0 because strlen() returns a size_t (unsigned integer). If the string were empty, str_length - 1 would 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 06:38:10