C语言---char *与const char *

一、const char和char

const char*的类型是:“指向一个具有const限定符的char类型的指针”。(不能修改其值)

char*的类型是:“指向一个char类型的指针”。

因此const char和char都是指向char类型的指针,只不过const char*指向的char类型是const的。

因此对于代码:

char* src; 
const char* dest ; 
dest = src;

这样赋值是正确的,因为:

  • 操作数指向的都是char类型,因此是相容的
  • 左操作数具有有操作数所指向类型的全部限定符(右操作数没有限定符),同时自己有限定符(const)

如果反过来赋值就违反了赋值的约束条件:src指向的对象的值可以修改,而dest指向的对象的值不可修改
如果让src去指向dest所指向的那个不可修改的对象,如果合法,岂不是变得可修改了?

src = dest; // 这样赋值,左操作数指向的类型没有右操作数指向类型的const限定符,不符合约束条件2

二、MS-RTOS代码演示

函数声明:

/**
 * @brief Get the name of a specified process.
 *
 * @note Cannot be called in the interrupt environment
 * @note Cannot be called in kernel lock environment
 *
 * @param[in] pid               Process id
 * @param[out] name             Process name buffer
 * @param[in] len               Process name buffer length(MUST >= MS_KERN_OBJ_NAME_SIZE)
 *
 * @return Error number
 */
ms_err_t ms_process_name(ms_pid_t pid, char *name, ms_size_t len);

/**
 * @brief Search a process by name.
 *
 * @param[in] name              The name of process
 * @param[out] pid              Process id
 *
 * @return Error number
 */
ms_err_t ms_process_find(const char *name, ms_pid_t *pid);

代码实例:

#include <ms_rtos.h>

int main (int argc, char **argv)
{
    
    
    ms_pid_t   pid;
    ms_pid_t   *fpid;
    char       buf[MS_KERN_OBJ_NAME_SIZE];
    char       *name;
    const char *find_name;

    pid = ms_process_self();
    ms_printf("process id is %d\n", pid);

    ms_process_name(pid, buf, MS_KERN_OBJ_NAME_SIZE);
    name = buf;
    ms_printf("process name is %s\n", name);

    fpid = &pid;
    find_name = name;

    ms_printf("find the process which name is %s pid is %d\n", find_name, *fpid);
    int ret = ms_process_find(find_name, fpid);

    if(ret >= 0) {
    
    
        ms_printf("find the process sucessful!\n");
    } else {
    
    
        ms_printf("fail to find the process!\n");
    }


    return  (0);
}

猜你喜欢

转载自blog.csdn.net/qq_40390825/article/details/115512323