0

I am trying to understand why this statement doesn't work.

char resp[] = "123456789";
void getValue(char *im)
{
   im = resp;
   printf("\n%s\n",im);
}

int main(int argc, char *argv[])
{
    char imei[11] = {0};
    getValue(imei);
    printf("\nIMEI: %s\n",imei);
    return 0;
}

Output:

123456789
IMEI: 
Hgaur
  • 109
  • 3
  • 10

3 Answers3

3

You can not assign with =, use strcpy instead:

#include <stdio.h>
#include <string.h>

char resp[] = "123456789";
void getValue(char *im)
{
   im = strcpy(im, resp);
   printf("\n%s\n",im);
}

int main(int argc, char *argv[])
{
    char imei[11] = {0};
    getValue(imei);
    printf("\nIMEI: %s\n",imei);
    return 0;
}

That's because imei is an array[11] (not just a pointer to), if you want to assign via = you can:

#include <stdio.h>

char resp[] = "123456789";
void getValue(char **im)
{
   *im = resp;
   printf("\n%s\n",*im);
}

int main(int argc, char *argv[])
{
    char *imei; /* Not an array but a pointer */
    getValue(&imei);
    printf("\nIMEI: %s\n",imei);
    return 0;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • Perhaps it would be worthwhile to explain the reason instead of just spoon-feeding OP with the ready-made "gimme teh codez". –  Aug 24 '13 at 06:27
  • Thanks for your reply, but I just need to know why doesn't this value reflect after the function. – Hgaur Aug 24 '13 at 06:29
  • H2CO3, you are right, I will try, but my english is not so good ;) – David Ranieri Aug 24 '13 at 06:33
2

C passes parameters by value. Whatever change you ale to the im will be lost when the function exits. If you want to preserve the change. Pass the address of the pointer. Then you can change the pointer at the address you pass.

Caleb
  • 124,013
  • 19
  • 183
  • 272
  • Thanks for replying, but isn't the array always passed as reference? – Hgaur Aug 24 '13 at 06:29
  • This is exactly the point I was trying to make. Caleb and Alter Man are correct: 1) If you want to copy the contents of resp into imei, the use `strcpy()`. 2) If you want to make imei point to resp, then you must use `getValue(char **im)`. – paulsm4 Aug 24 '13 at 17:22
1

Try this:

char resp[] = "123456789";

void getValue(char **im)
{
   *im = resp;
   printf("\n%s\n",*im);
}

You need to pass a pointer to a pointer as your program argument.

paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • 4
    This doesn't seem like it was the questioners intent. He allocated space to hold the copied string in imei. – dcaswell Aug 24 '13 at 06:16