gpt4 book ai didi

c - 指针使用不正确导致输出错误?

转载 作者:行者123 更新时间:2023-11-30 20:55:04 26 4
gpt4 key购买 nike

我有一个已完全填充的结构。这个名字是strdup'd。我想要做的是,创建一个指针数组,其中数组中的元素指向该 strdup 的变量。

这是我尝试过的:

struct Student{
char *name;
int age;
}Student;

void storeAdrress(const Student *student1,char **arrayOfPointers){
arrayOfPointers[0] = student1->name;

printf("Struct variable: %p",student1->name);
printf("Pointer variable: %p",arrayOfPointers[0]);
}

int main(void){
Student *student1 = calloc(1,sizeof(Student));
student1->name = strdup("Tom");

char *arrayOfPointers[100] = {0};

storeAdrress(student1,arrayOfPointers);

free(student1->name);
free(student1);

return(0);
}

这是我的输出:

Struct variable: (0x5502a80)
Pointer variable: (nil)

我的目标是让arrayOfPointers[0]获得名称的地址。这显然不起作用,因为 arrayOfPointers[0] 没有存储指针位置。

有人可以告诉我我做错了什么吗?

最佳答案

Weather Vane 击败了我,但这里是对您的代码的额外更正,没有使用 typedef,并添加了一些错误检查:

#define _POSIX_C_SOURCE 200809L

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

struct Student{
char *name;
int age;
};

void storeAddress(struct Student * stdt, char ** pArray, size_t index)
{
pArray[index] = stdt->name;
printf("Struct variable: %p\n", (void *) stdt->name);
printf("Pointer variable: %p\n", (void *) pArray[index]);
}

int main(void)
{
struct Student *student1 = calloc(1,sizeof(*student1));
if ( !student1 ) {
perror("couldn't allocate memory for struct Student");
exit(EXIT_FAILURE);
}

student1->name = strdup("Tom");
if ( !student1->name ) {
perror("couldn't allocate memory for student name");
exit(EXIT_FAILURE);
}

char *arrayOfPointers[100] = {0};

storeAddress(student1, arrayOfPointers, 0);

free(student1->name);
free(student1);

return 0;
}

输出:

Paul@Pauls-iMac:~/Documents/src/sandbox/names$ ./names
Struct variable: 0x7fd632403210
Pointer variable: 0x7fd632403210
Paul@Pauls-iMac:~/Documents/src/sandbox/names$

关于c - 指针使用不正确导致输出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35488915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com