gpt4 book ai didi

c - 当您将整数值类型转换为 char 指针时会发生什么?

转载 作者:太空宇宙 更新时间:2023-11-04 00:44:41 25 4
gpt4 key购买 nike

例如,

char * integerToString(void);

int main() {
char *myString;
do {
myString = integerToString();
} while (myString == (char *)-1); // worked as intended
free(myString);
return 0;
}

char * integerToString(void) {

int userInput;
printf("Enter an integer: ");
scanf("%d", &userInput);

if (userInput < 0 || userInput > 99)
return (char *)-1; // what happens here?

char *myString = (char *)malloc(sizeof(char) * 2);
myString[0] = (int)floor(userInput/10.0) + '0';
myString[1] = userInput%10 + '0';
return myString;
}

并且程序按预期工作,但是当您将整数值(没有将整数分配给变量)键入字符指针时,究竟会发生什么?这个程序会一直有效吗?谢谢。

最佳答案

C99:

6.3.2.3 Pointers

  1. An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

[...]

  1. An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.

因此将-1 转换为指针具有实现定义的结果。因此答案是否定的:这不能保证在一般情况下有效。


特别是:如果它确实是一个陷阱表示,您的代码将与以下方面发生冲突:

6.2.6 Representation of types

6.2.6.1 General

[...]

  1. Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. If such a representation is produced by a side effect that modifies all or any part of the object by an lvalue expression that does not have character type, the behavior is undefined. Such a representation is called a trap representation.

while (myString == (char *)-1); 如果 myString 是陷阱表示,则有未定义的行为。

关于c - 当您将整数值类型转换为 char 指针时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47617439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com