c - 如何检查 char * 是否为空?

标签 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";
    }

}

最佳答案

指针不是“空的”,它们要么指向有效数据,要么指向无效数据。使它们指向无效数据的一种受控方法是将它们分配给 NULL。因此,编写程序的正确方法是:

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

...

void store_stuff(char **name, int *age) {
  if(*name == NULL)
  {
    // handle error
  }
  ...
}

关于c - 如何检查 char * 是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50644885/

相关文章:

c# - 字符串生成器和字符串大小

C 指针 malloc

pointers - 空指针定义在计算机的哪一层?

c++ - 将指针分配给特定内存地址并更改其值后出现段错误

c - nodejs从C接收到的buffer分为两部分

MySQL CONCAT ("string",longtext) 生成十六进制字符串

c++ - c&c++默认全局变量链接,多重声明&定义问题

sql - 甲骨文 : String Concatenation is too long

c - C中的struct由1个字段组成,是同一类型的字段吗?

c - libpng 和 numpy 的平均 vector 计算结果不同