如何检查 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/