gpt4 book ai didi

无法确定为什么指针变量不会在该程序中寻址字符串中的元素?

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:54 25 4
gpt4 key购买 nike

我正在尝试使用指针变量来访问字符串的元素,但我的代码出现了问题,生成了编译错误:

#include <stdio.h>
#define MAX 29

char arrayI[250];
char *ptr;

int main(void)
{
ptr = arrayI;

puts("Enter string to arrayI: up to 29 chars:\n");
fgets(arrayI, MAX, stdin);

printf("\n Now printing array by pointer:\n");
printf("%s", *ptr);


ptr = arrayI[1]; //(I set the pointer to the second array char element)
printf("%c", *ptr); //Here is where I was wanting to use my pointer to
//point to individual array elements.
return 0;
}

我的编译器提示:

[警告] 赋值从整数生成指针而不进行强制转换 [默认启用]

我没有看到我的指针在哪里分配给整数数据类型?有人可以解释为什么我尝试实现指针变量失败了吗?谢谢大家!

最佳答案

#include <stdio.h>
#define MAX 29
// An array declaration that can hold upto 250 characters
char arrayI[250];
// A pointer variable that can hold the address of a character
char *ptr;
int main(void)
{
// Assigning the array's base address to the pointer variable
ptr = arrayI;
puts("Enter string to arrayI: up to 29 chars:\n");
fgets(arrayI, MAX, stdin);

printf("\n Now printing array by pointer:\n");
// Printing the entire array
printf("%s", ptr);

// Now modifying the pointer variable to point to the second character
ptr = &arrayI[1];
// Printing the second character from left in the array
printf("%c", *ptr);
}

假设内存分配如下:

假设基地址从4000开始。

      +----------+
4000 | | arrayI[0]
+----------+
4001 | | arrayI[1]
+----------+
4002 | | arrayI[2]
+----------+
.
.
.
+----------+
4249 | | arrayI[249]
+----------+

Now ptr = arrayI => 4000

printf("%s",ptr); //Print the entire string starting from address 4000

Now ptr = &arrayI[1] => 4001

printf("%c", *ptr); // Print valueAt(ptr) => valueAt(4001) => second character of arrayI

关于无法确定为什么指针变量不会在该程序中寻址字符串中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19898498/

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