Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
83 views
in Technique[技术] by (71.8m points)

c - How to access elements of array when parameter is double pointer?

First function changes big letter to small. In main I need to have five strings and with function konvertuj I have to go through that array and check for each letter if it's big and convert it to small. The point is that I don't know how to access each character of string in the function. (It's study example so it has to be done with these predefined functions.

char v2m(char z){
        char m = z + 0x20;
        return m;
    }
    void konvertuj(char **niz, int n){
        for (int i = 0; i < n; i++)
            if(*niz[i] > 'A' && *niz[i] < 'Z')
            *niz[i] = v2m(*niz[i]);
    }
    int main(){
        char **niz;
        niz[0] = "Voda";
        niz[1] = "KraISSa";
        niz[2] = "somsssR";
        niz[3] = "aaaaa";
        niz[4] = "WeWeWeW";
        for (int i = 0; i < 5; i++)
        {
            int d = -1;
            while(niz[i][++d]);
            konvertuj(&niz[i], d);
            printf("%s ", niz[i]);
        }
    }
question from:https://stackoverflow.com/questions/65905374/how-to-access-elements-of-array-when-parameter-is-double-pointer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. v2m - no need of the variable m

  2. konvertuj no need to iterate through the same letters all over again. You want to convert 1 letter as you iterate in main. Your condition is wrong as you will ignore 'A' and 'Z'

  3. Pointer to pointer does not have allocated space to accommodate 5 pointers. You need to allocate this space. In your code is it UB.

3.a You assign the pointers to the string literals. Attempt to modify the string literal invokes Undefined Behaviour. In my code, I use compound literals which are modifiable.

3.b use correct type for indexes (size_t).

char v2m(char z){
    return z + 0x20;
}
void konvertuj(char *niz, size_t n){
    if(niz[n] >= 'A' && niz[n] <= 'Z')
        niz[n] = v2m(niz[n]);
}

int main(void){
    char **niz = malloc(5 * sizeof((*niz)));
    niz[0] = (char[]){"Voda"};
    niz[1] = (char[]){"KraISSa"};
    niz[2] = (char[]){"somsssR"};
    niz[3] = (char[]){"aaaaa"};
    niz[4] = (char[]){"WeWeWeW"};
    for (size_t i = 0; i < 5; i++)
    {
        size_t d = 0;
        while(niz[i][d])
            konvertuj(niz[i], d++);
        printf("%s ", niz[i]);
    }
}

As I( understand you need to keep the function names types and parameters


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...