简体   繁体   English

Linux <-> Windows存储字符串地址

[英]Linux <-> Windows Storing an address of string

I have a serious problem with writing an App on Linux. 在Linux上编写应用程序时遇到严重问题。 I have this code 我有这个代码

#include <stdio.h>

int main()
{
    char ar[10][10];
    strcpy(ar[1], "asd");
    strcpy(ar[2], "fgh");

    int test[2];
    test[1] = (int)ar[1];
    printf("%s %x | %s %x\n\n", ar[1], ar[1], test[1], test[1]);

    return 0;
}

And it works on Windows well, but when i want to run this on Linux i got Segmentation Fault or Unauthorized Access to memory. 它在Windows上运行良好,但是当我想在Linux上运行时,出现了Segmentation Fault或对内存的未授权访问。

Your program invokes undefined behavior. 您的程序调用未定义的行为。 It assumes that a pointer will fit into an int , which isn't required. 它假定一个指针将适合int ,这不是必需的。 Usually pointers will fit on Unix boxes and fail on Windows; 通常,指针将适合Unix机器,而在Windows上将失败。 but you should use an appropriate integer type, such as intptr_t from stdint.h if you need to do such conversions. 但是如果需要进行此类转换,则应使用适当的整数类型,例如stdint.h intptr_t Note that strictly speaking the integer must be cast back to a pointer type before being passed to printf . 请注意,严格来讲,整数必须在传递给printf之前printf转换为指针类型。

Using a pointer type to printf and a large enough integral type results in correct behavior: http://ideone.com/HLExMb 使用指针类型来printf和足够大的整数类型会导致正确的行为: http : //ideone.com/HLExMb

#include <stdio.h>
#include <stdint.h>

int main(void)
{
    char ar[10][10];
    strcpy(ar[1], "asd");
    strcpy(ar[2], "fgh");

    intptr_t test[2];
    test[1] = (intptr_t)ar[1];
    printf("%s %x | %s %x\n\n", ar[1], ar[1], (char*)test[1], (char*)test[1]);

    return 0;
}

Note though that casting pointers into integral types is generally frowned upon and is likely to result in program bugs. 请注意,尽管通常将指针转换为整数类型并不容易,并且可能会导致程序错误。 Don't go there unless you absolutely need to do so for one reason or another. 除非您出于某种原因而绝对需要这样做,否则不要去那里。 When you're starting out in C it is unlikely that you'll ever need to do this. 当您开始使用C语言时,您不太可能需要这样做。

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

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