【问题标题】:print returned char* value [duplicate]打印返回的 char* 值 [重复]
【发布时间】:2019-12-16 11:16:39
【问题描述】:

我有这个代码,它的函数必须返回给定的字符串而不带一些符号。问题是我在打印 badWords 函数的返回值时遇到问题。它打印“????”我不知道怎么做。

#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>

char * badWord(int, char*);

int main(int argc, char **argv){
    char s[100]="O joao` foi as compra's, comprou um umb'igo! falante por £233";
    int n = sizeof(s);

    char* word = badWord(n, s);
    printf("%s\n", word);
}

char * badWord(int n, char s[n]){
    char palavra[n];
    int index=0;
    for(int i=0; i<n; i++){
        char c = s[i];
        char c2 = s[i+1];

        if(isalnum(c) || (ispunct(c) && isalpha(c2))){
            palavra[index]=c;
            index++;
        }
    }
    return palavra;
}

【问题讨论】:

  • palavra 是一个本地数组......
  • 您不能将本地分配的内存返回给调用者。当函数结束并且是未定义的行为时,它会被释放。
  • @André Morais 有什么功能?
  • char * badWord(int n, char s[n]) ---> void badWord(int n, char s[n], char palavra[n]);
  • @LPs 正确。或者,更好的是:int badWord(int n, char s[n], char palavra[n]);,其中函数可以检查错误参数(例如 NULL 指针)并在成功时返回 0,在失败时返回 -1。

标签: c string char word


【解决方案1】:

解决了!读取 cmets,我将本地数组“palavra”转换为全局数组,并且成功了!

#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>

char * badWord(int, char*);

int main(int argc, char **argv){
    char s[100]="O joao` foi as compra's, comprou um umb'igo! falante por £233";
    int n = sizeof(s);

    char* word = badWord(n, s);
    printf("%s\n", word);
}
char palavra[10000000];
char * badWord(int n, char s[n]){
    int index=0;
    for(int i=0; i<n; i++){
        char c = s[i];
        char c2 = s[i+1];

        if(isalnum(c) || (ispunct(c) && isalpha(c2))){
            palavra[index]=c;
            index++;
        }
    }
    return palavra;
}

【讨论】:

  • 您可以编写更好的代码...
  • 是的,对不起,我开始了
猜你喜欢
  • 2021-02-04
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 2019-07-13
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多