2
I’m trying to pass a array of char
for a Procedure that will be resized (with malloc()
), write your content 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 back to function main()
it is with the initial values, follows example code:
#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?
What’s the point? The function is pretty weird, does things kind of meaningless.
– Maniero
I did just one example to try to isolate the problem I am having when reading a serial port, what I want is: 1. pass a char array to a Procedure 2. resize that array in the Procedure 3. write values in that array 4. return the main with the dimentional array and with the new values
– fdavid
That is, when returning to the main the vector has to be all filled with 'x' and have size of 10 bytes.
– fdavid
You start working with a string, then shaken into this, which is right, is a string or not?
– Maniero
The correct thing is to work all the time with a string, I may be wrong about this, but it has to be dynamic.
– fdavid
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).
– Maniero