Vector of char by reference

2
I'm trying to pass a array from char to a procedure that will resize (with malloc() ), write its contents and return to main() .

I know that every vector is a pointer and is already passed by reference, but something in my software is not letting this happen, when I go back to the function main() it is with the initial values, it follows example code: p>

#include <stdio.h>
#include <stdlib.h>

void proc(char msg[])
{
    unsigned int i;

    msg = malloc(sizeof(char) * 10);

    msg[0] = 'a';
    msg[1] = 'b';
    msg[2] = 'c';
    msg[3] = 'd';
    msg[4] = 'e';
    msg[5] = 'f';
    msg[6] = 'g';
    msg[7] = 'h';
    msg[8] = 'i';
    msg[9] = 'j';

    for (i = 0; i<10; i++) {
        printf("%c\n", msg[i]);
        msg[i] = 'x';
    }

    printf("\n");
}

int main ()
{
    char msg[] = "12345";
    unsigned int i;

    printf("Before proc\n");

    for (i = 0; i<5; i++) {
        printf("%c\n", msg[i]);
    }

    printf("\nin proc ======\n");

    proc( msg );

    printf("After proc\n");

    for (i = 0; i<10; i++) {
        printf("%c\n", msg[i]);
    }

    printf("FIM");
    return 0;
}

The output is as follows:

bash-4.2$ ./a.out
Before proc
1
2
3
4
5

in proc ======
a
b
c
d
e
f
g
h
i
j

After proc
1
2
3
4
5





FIM

Where am I going wrong?

    
asked by anonymous 01.11.2017 / 18:03

1 answer

1

There are several errors and complications. I kept the scripts to see it working, but obviously that should not be there.

If you're going to work with string do it all the time like this. You need to have room for the terminator .

If you are going to change the size then you need to allocate the array dynamically with malloc() .

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

void proc(char msg[]) {
    msg = realloc(msg, 11);
    strcpy(msg, "xxxxxxxxxx");
    printf("\nin proc ======\n%s\n", msg);
}

int main() {
    char *msg = malloc(6);
    strcpy(msg, "12345");
    printf("Before proc\n%s", msg);
    proc(msg);
    printf("After proc\n%s\nFIM", msg);
}

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

I did not release the memory with free() because in theory I would use it elsewhere.

I did not check if the allocation worked, which makes the code less robust. The normal thing is to do this with malloc() and realloc() .

But in certain contexts none of these are correct and need a very different solution, especially in embedded environments.

    
01.11.2017 / 18:49