微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

执行功能后,为什么指针保存的数据不能保存?

如何解决执行功能后,为什么指针保存的数据不能保存?

我感到困惑的是,在将字符串数组的地址存储在函数内部的指针中之后,它没有返回我该字符串,而是看起来像一个地址。由于p已经存储了数组的地址,为什么它不打印相应的字符串?

代码如下:

#include <stdio.h>
#include <string.h>
#define SIZE 10
void findMinMaxStr(char word[][40],char *first,char *last,int size);
int main()
{
  char word[SIZE][40];
  char first[40],last[40];
  int i,size;
  printf("Enter size: \n");
  scanf("%d",&size);
  printf("Enter %d words: \n",size);
  for (i=0; i<size; i++)
    scanf("%s",word[i]);
  findMinMaxStr(word,first,last,size);
  printf("First word = %s,Last word = %s\n",last);
  return 0;
}

void findMinMaxStr(char word[][40],int size)
{
  int i;
  first = word[0];
  last = word[0];
  for(i=0;i<size;i++){
    if(strcmp(last,word[i])<0)
      last = word[i];
    if(strcmp(first,word[i])>0)
      first = word[i];
  }
}

如果我在函数添加printf语句:

void findMinMaxStr(char word[][40],word[i])>0)
      first = word[i];
  }
    printf("first : %s,last: %s\n",last);
}

它可以向右打印字符串。

解决方法

C对函数参数使用按值传递,并且指针本身按值传递。换句话说,您可以更改指针变量中存储的地址所指向的内容,但不能更改指针变量本身。

在函数内部进行更改

  last = word[i];  //updates the pointer itself,which will not reflect in the caller

  strcpy(last,word[i]);  // copy the content to the memory pointed to by pointer
, C中的

函数参数是所传递内容的副本,因此对它们的修改(赋值)不会影响所传递的内容。

在这种情况下,将传递从数组转换的指针,因此仅更改参数似乎不太好。

要复制字符串,应使用identity = lambda x: x def plus(y): return lambda x: x+y def nine(op=identity): return op(9) print(nine(plus(nine()))) # 18 而不是分配指针。

strcpy()

或者,您可以将指针存储在循环中,并在循环后复制结果字符串。

void findMinMaxStr(char word[][40],char *first,char *last,int size)
{
  int i;
  strcpy(first,word[0]);
  strcpy(last,word[0]);
  for(i=0;i<size;i++){
    if(strcmp(last,word[i])<0)
      strcpy(lasy,word[i]);
    if(strcmp(first,word[i])>0)
      strcpy(first,word[i]);
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。