【问题标题】:Why Can't the data pointed by pointer saved after executing the function?为什么函数执行后指针指向的数据不能保存?
【发布时间】:2021-02-23 09:56:36
【问题描述】:

我很困惑,在我将字符串数组的地址存储在函数内的指针中之后,它不会返回字符串,而是看起来像地址。既然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", first, last);
  return 0;
}

void findMinMaxStr(char word[][40], char *first, char *last,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], char *first, char *last,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("first : %s, last: %s\n",first,last);
}

它可以正确打印字符串。

【问题讨论】:

    标签: arrays c string function-pointers void-pointers


    【解决方案1】:

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

    在这种情况下,从数组转换的指针被传递,所以简单地改变参数似乎并不好。

    要复制字符串,您应该使用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]);
      }
    }
    

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

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

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-26
        • 2012-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多