M
Mike
Hi,
Can someone tell me where I'm going wrong please?
I'm trying to read 6 strings, allocate memory for each one and then print
them to screen before finally freeing the memory.
This is what I'm working with at the moment:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main(void)
{
/*Array for holding pointers to the strings */
char *str_array[6];
/*Variable to keep track of which string we're working on*/
int string;
/*Temp string to hold value after it has been read */
char tempstr[40];
for (string=0; string<6; string++){
/*Read string */
scanf("%s", tempstr);
/*Allocate memory for the string, save address in str_array */
str_array[string]=(char*)(malloc(strlen(tempstr)*sizeof(char)));
/*Copy read string to newly created memory*/
*str_array[string] = tempstr;
}
for (string=0; string<6; string++){
/*Print the string*/
printf("%s\n", str_array[string]);
/*String has finished so free memory at that location*/
free(str_array[string]);
}
return 0;
}
At the moment it's currently displaying a random set of characters however
from stepping through the code I've noticed that the strings are being
stored in the str_array and not the actual space I'm allocating for them.
I'm presuming that the error is line:
*str_array[string] = tempstr;
However that to me looks right....
Any help appreciated,
Cheers,
Mike
Can someone tell me where I'm going wrong please?
I'm trying to read 6 strings, allocate memory for each one and then print
them to screen before finally freeing the memory.
This is what I'm working with at the moment:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main(void)
{
/*Array for holding pointers to the strings */
char *str_array[6];
/*Variable to keep track of which string we're working on*/
int string;
/*Temp string to hold value after it has been read */
char tempstr[40];
for (string=0; string<6; string++){
/*Read string */
scanf("%s", tempstr);
/*Allocate memory for the string, save address in str_array */
str_array[string]=(char*)(malloc(strlen(tempstr)*sizeof(char)));
/*Copy read string to newly created memory*/
*str_array[string] = tempstr;
}
for (string=0; string<6; string++){
/*Print the string*/
printf("%s\n", str_array[string]);
/*String has finished so free memory at that location*/
free(str_array[string]);
}
return 0;
}
At the moment it's currently displaying a random set of characters however
from stepping through the code I've noticed that the strings are being
stored in the str_array and not the actual space I'm allocating for them.
I'm presuming that the error is line:
*str_array[string] = tempstr;
However that to me looks right....
Any help appreciated,
Cheers,
Mike