我正在尝试使用指针变量来访问字符串的元素,但我的代码出现了问题,生成了编译错误:
#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
我是一名优秀的程序员,十分优秀!