使用指针到指针时无法理解我的错误(C)

时间:2018-04-27 19:15:35

标签: c

#include <stdio.h>

#define TEMP_SIZE 50

void getUserInput(char ** arr, char * temp, int size);
int welcomeAndGetSize(char ** arr);
/*
This Code is taking from the user his number of friends and allocating a pointer to a pointer,in each index its inputes the name of his friends and then sorting the names
via alphabetical order
*/
int main(void)
{
    int i = 0;
    int size = 0;
    char ** stringArray = 0;
    char tempStore[TEMP_SIZE] = { 0 };
    size = welcomeAndGetSize(stringArray);
    getUserInput(stringArray, tempStore, size);
    for (i = 0; i < size; i++)
    {
        printf("%s\n",stringArray[i]);
    }
    free(stringArray);
    getchar();
    return 0;
}
/*
This Functions welcomes the user and gets the number of friends from him.
    input:the pointer to pointer array - char** arr.
        output:the number of firends - int size.
*/
int welcomeAndGetSize(char ** arr)
{
    int size = 0;
    printf("Please Enter Number Of Friends: ");
    scanf("%d",&size);
    getchar();
    arr = (char**)malloc(sizeof(char*) * size);
    return size;
}
/*
This Function gets frome the user the name of his friend and dynamically allocates the memry needed for the string
and inputes it in the pointer to pointer.
    input:the pointer to a pointer - char ** arr,a char array to temporarly store the string, the number of friends.
        output:none.
*/
void getUserInput(char ** arr,char * temp, int size)
{
    int i = 0;
    int j = 0;
    for (i = 0; i < size; i++)
    {
        printf("Please Enter The Name Of The %d friend: ",i + 1);
        fgets(temp,TEMP_SIZE,stdin);
        for (j = 0; j < strlen(temp); j++)
        {
            if ('\n' == temp[j])
            {
                temp[j] = 0;
            }
        }
        arr[i] = (char*)malloc(sizeof(char) * strlen(temp));
        arr[i] = temp;
    }

}

这段代码是我在课堂上的作业,在使用指针指针时我犯了一个错误,我知道代码中的错误在哪里, 它在函数getUserInput:

    arr[i] = (char*)malloc(sizeof(char) * strlen(temp));
    arr[i] = temp;

我得到以下消息:

抛出异常:写入访问冲突。 arr是0x1110112。发生 请解释为什么我得到这个错误msessge。 (p.s我使用Visual Studio)

2 个答案:

答案 0 :(得分:2)

我在此代码中看到多个错误。但是,导致您的写入访问冲突的初始问题与您的welcomeAndGetSize功能有关。有一个更简单的例子:

void funcB(int* value) {
    value = (int*)malloc(sizeof(int*));
}

void funcA() {
    int* number = NULL;
    funcB(number);
    // number is still NULL
}

在funcA结束时,number仍然未设置,并且你已经泄露了一些内存。相反,你想做类似的事情:

void funcB(int** value) {
    *value = (int*)malloc(sizeof(int*));
}

void funcA() {
    int* number = NULL;
    funcB(&number);
    // number is allocated
}

您需要以类似的方式调整代码以分配stringArray

此外,另一个答案是正确的 - 而不是arr[i] = temp;您可能需要strcpy(arr[i], temp);

答案 1 :(得分:1)

 arr[i] = (char*)malloc(sizeof(char) * strlen(temp) + 1);
 strcpy(arr[i],temp);

=不复制字符串

并在主

stringArray = malloc(size * sizeof(char *));
之前

btu你需要以某种方式初始化size