1

这是我的代码:

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

void getinfo(unsigned int a, unsigned int b, char **s);

int main(){
    unsigned int len_max = 8;
    unsigned int current_size = 0;
    char *pStr = malloc(len_max);
    if(pStr == NULL){
        perror("\nMemory allocation\n");
        return EXIT_FAILURE;
    }
    current_size = len_max;

    printf("Inserisci hostname: ");
    getinfo(len_max, current_size, &pStr);
    printf("\nLa stringa inserita è: %s\n", pStr);
    free(pStr);
    return EXIT_SUCCESS;
}

void getinfo(unsigned int a, unsigned int b, char **pStr){
    unsigned int i = 0;
    char c = EOF;
    while((c = getchar()) != '\n'){
        *pStr[i++] = (char)c;
        if(i == b){
            b = i+a;
            if((*pStr = realloc(*pStr, b)) == NULL){
                perror("\nMemory allocation error\n");
                exit(EXIT_FAILURE);
            }
        }
    }
    *pStr[i]='\0';
}

当我执行此代码时,当我按下回车键时(在我写完字符串之后)出现分段错误。
我确定问题出在函数中(可能问题出在 *s 指针上),但我不知道如何纠正它......

4

2 回答 2

3

你有一个优先级问题。你需要使用

(*s)[i++] = ...

代替

*s[i++] = ...

同样你需要

(*s)[i]='\0';

当您编写时,*s[i]您正在索引s. 但是你想索引*s,因此需要括号。

我没有检查您的其余代码,但如果确实有更多错误,我希望这可以帮助您调试其余代码。

于 2012-05-05T16:47:35.963 回答
1

问题在于*s[i++] = (char)c;尝试(*s)[i++] = (char)c;用 *s 周围的括号将其转换为。以及(*s)[i] = '\0'.

于 2012-05-05T16:52:21.927 回答