如何不使两个指针指向同一地址?

问题描述 投票:-1回答:1

所以目前,我正在尝试制作一个与列表数组相同的临时数组。我试图使临时数组中的单词全部变为大写,并且使其正常工作,但同时也使列表数组中的单词变为大写。我不希望这种情况发生,所以我假设列表数组已更改,因为两个双指针都指向相同的地址。您能帮我解决这个问题吗?

void searchPuzzle(char** arr, int n, char** list, int listSize) {
    // This function checks if arr contains words from list. If a word appears
    // in arr, it will print out that word and then convert that word entry in
    // arr to lower case.
    // Your implementation here.
    char** tempList = malloc(50 * sizeof(char**));
    char* temp;
    int i;

    for (i = 0; i < 50; i++) {
        *(tempList + i) = *(list + i);
    }

    for (i = 0 i < listSize; i++) {
        for (temp = *(tempList + i); *temp != '\0'; temp++) {
            if (*temp >= 'a' && *temp <= 'z') {
                *temp = *temp - 32;
            }
        }
        printf("%s\n", *(tempList + i));
    }
}
c memory-address uppercase double-pointer
1个回答
0
投票

如果在函数声明后阅读注释

// This function checks if arr contains words from list. If a word appears
// in arr, it will print out that word and then convert that word entry in
// arr to lower case.
// Your implementation here

然后似乎您需要的是以下内容。我只将int类型替换为size_t类型的函数参数。

#include <string.h>
#include <ctype.h>

void searchPuzzle( char **arr, size_t n, char **list, size_t listSize ) 
{
    // This function checks if arr contains words from list. If a word appears
    // in arr, it will print out that word and then convert that word entry in
    // arr to lower case.
    // Your implementation here

    for ( size_t i = 0; i < n; i++ )
    {
        size_t j = 0;

        while ( j < listSize && strcmp( arr[i], list[j] ) != 0 ) ++j;

        if ( j != listSize )
        {
            puts( arr[i] );

            for ( char *p = arr[i]; *p; ++p )
            {
                *p = tolower( ( unsigned char )*p );
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.