簡體   English   中英

為什么指向自定義結構的指針在這里不起作用?

[英]Why does pointer to custom struct doesn't work here?

  1. 為什么指向自定義結構的指針在該代碼中不起作用?
  2. 為什么我在 p->x = x 的那一行收到警告?
  3. 為什么我收到與 strcpy_s 一致的第二次警告?
#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct sptr {
    int x;
    char* s;
    struct sptr* next;
} ptr;

void add(ptr* p, int x, const char* s) {
    ptr* o = p;
    p = (ptr*) malloc(sizeof(ptr));
    p->x = x; // warning
    p->s = (char*)malloc(20 * sizeof(char));
    strcpy_s(p->s, 20, (char*)s); // warning
    p->next = o;
}

void show(ptr* p) {
    ptr* o = p;
    while (o != NULL) {
        printf("%d %s\n", o -> x, o -> s);
        o = o->next;
    }
}

int main() {
    ptr* p = NULL;

    add(p, 5, "xcvxvxv");
    add(p, 7, "adadad");
    show(p);

    return 0;
}

指針是值。

add正在接收 NULL 指針值的副本 add中的局部變量p更改為malloc返回的新指針值不會更改main中單獨的局部變量p

就像您想更改調用者的 scope 中的int值一樣,您將使用int *參數:

void change(int *val)
{   
    *val = 10;
}                   
                                
int main(void)             
{
    int a = 5;             
    change(&a);
}

更改調用者 scope 中int *的值需要一個int **參數。

#include <stdlib.h>

void change(int **val)
{
    *val = malloc(sizeof **val);
}

int main(void)
{
    int *a;
    change(&a);
}

這擴展到任何類型。


malloc可能會失敗,並返回NULL 對 NULL 指針值執行間接尋址是未定義的行為

您必須通過檢查malloc的返回值來防止這種情況發生。

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

typedef struct node {
    int x;
    char *s;
    struct node *next;
} Node;

void add(Node **p, int x, const char *s) {
    Node *new_node = malloc(sizeof *new_node);

    if (!new_node) {
        perror("allocating node");
        exit(EXIT_FAILURE);
    }

    new_node->s = malloc(1 + strlen(s));

    if (!new_node->s) {
        perror("allocating node string");
        exit(EXIT_FAILURE);
    }

    new_node->x = x;
    strcpy(new_node->s, s);

    new_node->next = *p;
    *p = new_node;
}

void show(Node *p) {
    while (p) {
        printf("%d %s\n", p->x, p->s);
        p = p->next;
    }
}

int main(void) {
    Node *list = NULL;

    add(&list, 5, "xcvxvxv");
    add(&list, 7, "adadad");

    show(list);
}
  1. 為什么指向自定義結構的指針在該代碼中不起作用?

待定

  1. 為什么我在 p->x = x 的那一行收到警告?
  2. 為什么我收到與 strcpy_s 一致的第二次警告?

出現 2 個警告是因為代碼從malloc()中取消引用指針而沒有首先檢查指針是否為NULL

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM