Home > Software engineering >  How to use double ampersand or any other better alternative in c?
How to use double ampersand or any other better alternative in c?

Time:09-11

I am new to C. I used pointer but It does not work in the case when there is already an ampersand as two ampersands cannot be put. I made a strcpy_s function to make it easy to prevent L buffer is too small.

void strcpy_s_1(char** dest_str, char* str) {
    int len = strlen(str);
    *dest_str = (char*)malloc(len   1);
    strcpy_s(*dest_str, len   1, str);
}

but it causes issue in this function:

char* replaceWord(const char* s, const char* oldW,
    const char* newW)
{
    char* result;
    int i, cnt = 0;
    int newWlen = strlen(newW);
    int oldWlen = strlen(oldW);

    // Counting the number of times old word
    // occur in the string
    for (i = 0; s[i] != '\0'; i  ) {
        if (strstr(&s[i], oldW) == &s[i]) {
            cnt  ;

            // Jumping to index after the old word.
            i  = oldWlen - 1;
        }
    }

    // Making new string of enough length
    result = (char*)malloc(i   cnt * (newWlen - oldWlen)   1);

    i = 0;
    while (*s) {
        // compare the substring with the result
        if (strstr(s, oldW) == s) {
            strcpy_s_1(&&result[i], newW);
            i  = newWlen;
            s  = oldWlen;
        }
        else
            result[i  ] = *s  ;
    }
    result[i] = '\0';
    return result;
}

The original line of command was

strcpy_s(&result[i], sizeof(&result[i]), newW);

CodePudding user response:

The problem is that in C && is not a valid operator.

the & operator returns the value address of the variable.

Look at this code:

#include <stdio.h>

int main()
{
  int a = 1;
  int * p;
  int **q;

  p = &a;
  q = &p;

  printf(" &a %p, &p %p, &q %p \n", &a, &p, &q);
  printf(" a %d , p %p, q %p", a, p, q);
  return 0;
}

that shows:

&a 0x7ffcbe4cbba4, &p 0x7ffcbe4cbba8, &q 0x7ffcbe4cbbb0 
a 1 , p 0x7ffcbe4cbba4, q 0x7ffcbe4cbba8

As you can see the value of q is the same as &p, which means that the address of p is stored in q. But, if I try to do this:

printf(" &&q %p", &(&q));

it shows me this error:

main.c: In function ‘main’:
main.c:23:23: error: lvalue required as unary ‘&’ operand
23 |     printf(" &&q %p", &(&q));
   |                       ^

Because the "&" operator could be used just once, it return the value address, and in C there is no sense to "value address of the value address"

Hope this can help to understand the problem :)

  •  Tags:  
  • c
  • Related