如何检查char*是否为空?

Zoe*_*kov 0 c string pointers char

如何检查是否char *name为空?

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

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

    char *name;
    int age;

    store_stuff(&name, &age);

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

}

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

    *age = 31;

    if (name == NULL) { // how can I check here if char name is empty?
        *name = "ERROR";
    }

}
Run Code Online (Sandbox Code Playgroud)

Lun*_*din 7

指针不是"空",它们指向有效数据或无效数据.使它们指向无效数据的受控方式是将它们分配给NULL.因此,编写程序的正确方法是:

char *name = NULL;
int age;
store_stuff(&name, &age);

...

void store_stuff(char **name, int *age) {
  if(*name == NULL)
  {
    // handle error
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)