小编Nig*_*ife的帖子

函数调用后指针的值仍然可用?

#include <stdio.h>
//needed so we can use the built in function strcpy
#include <string.h>
int main()
{
char* foo()
    {
        char* test="Hello";
        printf("value of test: %p\n",test);
        return test;

    }


    //why does this work? is test off the stack, but Hello in mem is still there?
    work=foo();
    printf("value of work after work has been initalized by foo(): %p\n",work);
    printf("%s\n",work);
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,'work = foo()',作品我注意到'test'和'work'的值是相同的.这意味着它们指向内存中的相同点,但在函数调用'test'之后超出范围并且不允许访问.为什么不允许访问'test',但其值/内存位置是?我假设由于在函数调用后离开堆栈,不允许访问'test'?我是新手,所以如果我的术语或任何内容都关闭,请纠正我.

c pointers

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

确保我写入C中拥有的内存

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

struct Person
{
    unsigned long age;
    char name[20];
};

struct Array
{
    struct Person someone;
    unsigned long used;
    unsigned long size;
};

int main()
{
    //pointer to array of structs
    struct Array** city;
    //creating heap for one struct Array
    struct Array* people=malloc(sizeof(struct Array));
    city=&people;

    //initalizing a person
    struct Person Rob;
    Rob.age=5;
    strcpy(Rob.name,"Robert");

    //putting the Rob into the array
    people[0].someone=Rob;

    //prints Robert
    printf("%s\n",people[0].someone.name);
    //another struct
    struct Person Dave;
    Dave.age=19;
    strcpy(Dave.name,"Dave");
    //creating more space on the …
Run Code Online (Sandbox Code Playgroud)

c memory heap

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

标签 统计

c ×2

heap ×1

memory ×1

pointers ×1