我很难通过引用数组和指针来获取单个元素信息。另外,我无法重写指针值并将其传递回主引用。
任何帮助将不胜感激!
void strings(char word[][40], char *first, char *last, int size);
int main()
{
char word[10][40];
char first[40], last[40];
int i, size;
printf("Enter size: \n");
scanf("%d", &size); //storing size
printf("Enter %d words: \n", size);
for (i=0; i<size; i++)
scanf("%s", word[i]); //storing user input
deriving(word, first, last, size);
printf("First word = %s, Last word = %s\n", first, last);
return 0;
}
void deriving(char word[][40], char *first, char *last, int size)
{
int count = 0;
char *ptr = word; //why is it when i store the user input as a ptr variable i am able to get each element?
while(*ptr != '\0')
{
printf("number of lines = number of elements \n");
ptr++;
}
while(*(word+count) != '\0')
{
count ++;
printf(" element is present"); // it is stuck in a infinite loop here.
}
first = "first word"; //why does this two commands not carry into the main function? since i am rewriting the whole pointer
last = "last word";
}
对于初学者,此声明
char *ptr = word;
无效。根据参数word
的声明,初始化程序的类型为char(*)[40],例如
char word[][40]
并且没有从一种指针类型到另一种指针类型的隐式转换。
所以你必须写
char ( *ptr ) = word;
结果是这些循环
while(*ptr != '\0')
{
printf("number of lines = number of elements \n");
ptr++;
}
while(*(word+count) != '\0')
{
count ++;
printf(" element is present"); // it is stuck in a infinite loop here.
}
也是不正确的,因为未初始化数组字。
char word[10][40];
请注意,由于变量word
具有类型char ( * )[40]
,然后取消引用表达式*(word+count)
,您将获得类型char[40]
的对象。将该值与'\0'
进行比较是没有意义的,因为此比较等效于
*(word+count) != NULL
由于左操作数不是空指针,因此条件的值为真。
对于first
和last
,则它们是函数的局部变量,具有传递的参数值的副本,即它们包含用作函数参数的数组的第一个字符的地址。因此,更改局部变量不会影响原始数组。
此外,由于数组是不可修改的左值,因此您可能无法重新分配数组。
您必须将字符串文字复制到数组的元素。
例如
strcpy(first, "first word" );
strcpy( last, "last word" );