【发布时间】:2020-08-01 10:15:05
【问题描述】:
我使用 CodeBlocks for Windows 作为我的 IDE。我的程序有问题,我想了解一下。在我展示的程序中,我将一个变量声明为char*,然后我的程序将其转换为const char*。我希望这个char* 是只读的,但我可以修改,因为我不知道是什么原因。
这是我的代码:
#include <stdio.h>
#include <windows.h>
int main() {
int i, d;
char *array[5][5]; // This is the variable that I declare as char*
for (i = 0; i != 5; i++) {
for (d = 0; d != 5; d++) {
array[i][d] = " "; // I can change its value because it is a char* type variable
}
}
for (i = 1; i != 0; i++) {
printf("%s %s %s %s %s\n", array[0][0], array[0][1], array[0][2], array[0][3], array[0][4]);
printf("%s %s %s %s %s\n", array[1][0], array[1][1], array[1][2], array[1][3], array[1][4]);
printf("%s %s %s %s %s\n", array[2][0], array[2][1], array[2][2], array[2][3], array[2][4]);
printf("%s %s %s %s %s\n", array[3][0], array[3][1], array[3][2], array[3][3], array[3][4]);
printf("%s %s %s %s %s\n", array[4][0], array[4][1], array[4][2], array[4][3], array[4][4]);
array[0][0] = "AAA"; // Again I can change its value
array[1][0] = "BBB"; // And again...
Sleep(1000);//This is only to see the results
system("cls");
if (i == 5) {
array[0][0] = strdup(array[1][0]); // I was trying to copy two strings using the strcpy() but the program stopped, and the problem was that the destiny string was a const char* type string and that couldn't be, even though I could change it before
strcpy(array[0][0], array[1][0]);
}
}
return 0;
}
【问题讨论】:
-
"programm 把它变成一个 const char*":我不知道你的意思。你能准确解释你观察到的东西吗?编译器错误、运行时错误、意外行为?很可能解释与神奇地改变类型的对象不同。
-
@NateEldredge 这是一个运行时错误,当行“array[0][0] = strdup(array[1][0]);”不存在时,当 strcpy 行应该工作程序停止运行,并出现消息“进程返回-1073741819(0xC0000005)”。
-
const char*不包含数组;它包含一个指针。指针是常量。 -
了解
strcpy和malloc。正确的方式是:array[i][d] = malloc( 4 ); strcpy( array[i][d], " " ); -
char *array[5][5]没有声明char *。它声明了一个数组
标签: c pointers constants c-strings string-literals