有char指针的问题

时间:2018-06-01 11:37:19

标签: c function pointers

我遇到了char指针问题。我正在尝试从store_stuff函数中获取值并将其打印到main函数中。我怎么能这样做?

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

void store_stuff(char *name, int *age);
int main(void) {

    char *name;
    int age;

    store_stuff(&name, &age); // I'm having trouble here

    printf("Name: %s\n", name);
    printf("Age: %d\n", age);

}

void store_stuff(char **name, int *age) {

    *name = "John";
    *age = 31;

}

2 个答案:

答案 0 :(得分:0)

https://ideone.com/5HOPGQ

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

char *store_stuff(char **name, int *age);
int main(void) {

    char *name;
    int age;

    store_stuff(&name, &age); // I'm having trouble here

    printf("Name: %s\n", name);
    printf("Age: %d\n", age);

}

char *store_stuff(char **name, int *age) {

    *name = "John";
    *age = 31;
    return *name;
}

答案 1 :(得分:-1)

成功

void store_stuff(char** name, int* age)
{
    *name = "John";
    *age = 31;
}

您需要指向名称分配的指针才能超出store_stuff

您还需要更改

的定义

char name

char* name

由于name本身想要成为一个以字符串交互的指针

编辑:当然,请确保使用void store_stuff(char** name, int* age);

使您的原型在顶部保持一致