De-referencing char pointer run-time error
为什么下面的代码会导致运行时崩溃?
代码本身并不是很有用,但是,通过创建指向 char 指针并指向 main 中的字符串文字的指针,将此指针传递给我的函数并尝试读取字符串会导致问题。为什么会这样?
通过在 main 然而(注释掉)中创建一个字符串数组,传递和读取字符串没有问题。提前感谢您的知识。
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <stdio.h>
#include <stdlib.h> #include <string.h> char* GetString(char** strs, int strsSize); char* GetString(char** strs, int strsSize) int main() char** stringArr = {“ab”,“abc”,“abcd”}; char* resultStr; printf(“%s\ return 0; |
- 指针不是数组;数组不是指针。
- 为什么你使用的编译器没有提供关于 char** stringArr = {“ab”,”abc”,”abcd
- mingw. See them now. Why shouldn’t it be a compiler error rather than warnings?
- the posted code does not compile. When compiling, always enable all the warnings, then fix those warnings. (for gcc 的警告,至少使用:-Wall -Wextra -pendantic 我也使用:-Wconversion -std=gnu99)警告:未使用的参数:strsSize 可以通过插入语句 (void)strsSize; 来修复.并且 strArray 的声明不正确。
stringArr 的初始化程序无效。您有一个指向指针的指针,而不是数组。无法使用 {} 语法初始化指针。
使用 -Wall -Wextra 编译时,会产生以下警告:
1
2 3 4 5 6 |
/tmp/x1.c: In function a€?maina€?:
/tmp/x1.c:15: warning: initialization from incompatible pointer type /tmp/x1.c:15: warning: excess elements in scalar initializer /tmp/x1.c:15: warning: (near initialization for a€?stringArra€?) /tmp/x1.c:15: warning: excess elements in scalar initializer /tmp/x1.c:15: warning: (near initialization for a€?stringArra€?) |
注释掉的声明是正确的。
这两个声明都可以有效地传递给 GetString,因为数组在传递给函数时会衰减为指向第一个元素的指针。但是,指针和数组不是一回事。
来源:https://www.codenong.com/41467762/