小编Stu*_*art的帖子

为什么使用删除会导致核心转储?

我目前正在使用Kubuntu 19.04 Kate 18.12.3和g ++(Ubuntu 8.3.0-6ubuntu1)8.3.0自学C ++

在Kate的“工具/模式/源”菜单中,选择C ++或ISO C ++。

我已经编写了一个小程序,其目的是修复上一个练习中提出的蓄意的内存泄漏。这是我的代码。

/* Fix the program from Exercise 6. */

#include <iostream>

int myFunction(int * pInt);

int main()
{
    int myVar;
    int * pInt = new int;
    pInt = &myVar;
    *pInt = myFunction(&myVar);
    std::cout << "The value of myVar is " << *pInt << std::endl;
    delete pInt;   // Free up pointer.
    pInt = 0;      // Make pointer safe.
    return 0;
}

int myFunction(int * pInt)
{
    *pInt = 2;
    return …
Run Code Online (Sandbox Code Playgroud)

c++

2
推荐指数
1
解决办法
95
查看次数

scanf() 不写入二维字符数组

我正在阅读一本教科书,使用 Code::Blocks v20.03 IDE 自学 C 编程。

我真的被一个小程序迷惑了,该程序将三个小字符串读入一个二维字符数组,然后将它们打印到屏幕上。该程序的代码如下所示。

#include <stdio.h>

int main(void)
{
   char *colors[3][10] = {'\0'};

   printf("\nEnter 3 colors seperated by spaces: ");
   scanf("%s %s %s", colors[0][0], colors[1][0], colors[2][0]);

   printf("\nYour entered: ");
   printf("%s %s %s\n", colors[0][0], colors[1][0], colors[2][0]);
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译时错误或警告为零,执行时会产生以下输出。

您输入:(空)(空)(空)

使用 IDE 的 Watches 窗口显示没有任何内容写入数组。我知道数组名称被视为指向数组中第一个元素的指针。我还了解使用下标/索引来访问数组维度内的元素(例如整数数组),因此需要将这个 char 数组中的数组第二维保持为零。

可悲的是,这让我完全困惑,所以我需要帮助来填补我的理解空白。

此致,

斯图尔特

c runtime-error scanf c-strings multidimensional-array

2
推荐指数
1
解决办法
112
查看次数