【问题标题】:longestCommonPrefix returned from function but not printed to console in C从函数返回的最长公共前缀但未打印到 C 中的控制台
【发布时间】:2020-01-09 17:02:24
【问题描述】:

在下面的代码中,函数返回一个字符指针“p”并存储在“out”变量中,该变量也是一个指针。当我尝试使用 printf 语句打印时,它不会向控制台输出任何内容,是否有任何指针?

#include <stdio.h>
#include <string.h>

char * longestCommonPrefix(char **strs, int strsSize){
    int j = 0;
    char *p;
    char result[10];
    int len = strlen(result);
    while(j < strlen(strs[0])){
        if(strs[0][j] == strs[1][j] && strs[1][j] == strs[2][j]){
            result[len++] = strs[0][j];
        }
        j++;
    }
    result[len] = '\0';
    p = result;
    return p;
}

int main()
{
    char *arr[] = {"flower", "flow", "flight"};
    char **ptr; 
    char *out;
    int size = sizeof(arr) / sizeof(arr[0]);
    ptr = arr;
    out = longestCommonPrefix(ptr, size);//breakpoint here shows the expected output
    printf("%s", out); //does not print the output to console
}

【问题讨论】:

  • presultlongestCommonPrefix 的局部变量。函数返回后它们不再存在。
  • 一种解决方案是“返回指向输入字符串之一的指针和整数长度。在标准 C 中,您只能返回一件事,但您可以有一个指针参数,您可以为另一种。一种丑陋的解决方案是将索引返回到字符串之一和长度,然后将它们作为上限值和下限值存储在一个返回的整数中,但这限制了您可以处理的数组或字符串的大小.

标签: c pointers function-pointers


【解决方案1】:

感谢@Paul Ogilvie,我能够通过堆中的动态内存分配、strcpy 到指针并在本地内存不存在时返回指针来解决它,我正在打印。

#include <stdio.h>
#include <string.h>

char * longestCommonPrefix(char **strs, int strsSize){
    int j = 0;
    char* p = malloc(10 * sizeof *p);
    char result[10];
    int len = strlen(result);
    while(j < strlen(strs[0])){
        if(strs[0][j] == strs[1][j] && strs[1][j] == strs[2][j]){
            result[len++] = strs[0][j];
        }
        j++;
    }
    result[len] = '\0';
    strcpy(p, result);
    return p;
}

int main()
{
    char *arr[] = {"flower", "flow", "flight"};
    char **ptr;
    int size = sizeof(arr) / sizeof(arr[0]);
    ptr = arr;
    char *out = longestCommonPrefix(ptr, size);
    printf("%s\n", out);
    free(out);
}

【讨论】:

  • 将拨打malloc的那一行改成char* p = malloc(10 * sizeof *p);
猜你喜欢
  • 2022-01-11
  • 2011-12-23
  • 2021-09-11
  • 1970-01-01
  • 2012-02-01
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 2018-11-28
相关资源
最近更新 更多