小编use*_*647的帖子

全局变量的值在我的代码中如何变化?

我在main函数之后再次声明了全局变量,但是它仍然会影响main函数。我知道C允许在第一次声明不初始化变量时再次声明全局变量(它将在c ++中不起作用)。如果我在main函数之后分配值,则它在c中仍然会出现两个警告,但在c ++中会给出错误。

我已经调试了代码,但没有成功int a=10;

#include <stdio.h>
#include <string.h>

int a;

int main()
{
    printf("%d",a);
    return 0;
}
/*a=10  works fine with following warnings in c.
        warning: data definition has no type or storage class
        warning: type defaults to 'int' in declaration of 'a' [-Wimplicit-int]|

        but c++ gives the following error
        error: 'a' does not name a type|
*/
int a=10;
Run Code Online (Sandbox Code Playgroud)

输出为10

c global-variables

3
推荐指数
1
解决办法
110
查看次数

删除运算符在我的代码中如何工作?

如果要delete释放内存,那么为什么前两个元素被重置为其初始垃圾值,而其余两个元素却没有?删除指针后,我得到异常输出。请解释它是如何工作的以及为什么我得到这样的输出。

#include<iostream>

using namespace std;

int main()
{
    int i;
    int *q = new int[10];
    int *r;
    r=q;
    printf("%d %d\n",*r,*(r+1));

    for(i=0;i<10;i++)
        q[i]=100;

    delete[] q;

    for(i=0;i<10;i++)
    {
        cout<<"r="<<*(r+i)<<"   ";
        cout<<"q="<<*(q+i)<<"\n";
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

代码输出如下:

8389928 8388800 r = 8389928 q = 8389928 r = 8388800 q = 8388800 r = 100
q = 100 r = 100 q = 100 r = 100 q = 100 r = 100 q = 100 r = 100 q = 100 …

c++ memory-management

0
推荐指数
1
解决办法
70
查看次数

标签 统计

c ×1

c++ ×1

global-variables ×1

memory-management ×1