I'm trying to instantiate a new string every iteration of a loop. What I tried was this:
int main(void) {
char *strs[10];
for (int i = 0; i < 10; i++) {
char str[10] = "";
char c = '0' + i;
strncat(str, &c, 1);
strs[i] = str;
}
for (int i = 0; i < 10; i++) {
printf("%s\n", strs[i]);
}
}
However, this prints all 9's, since C has conveniently decided that each iteration it would use the same address. I know that the following works, but just wanted to ask if it is possible to avoid malloc.
int main(void) {
char *strs[10];
for (int i = 0; i < 10; i++) {
char *str = malloc(sizeof(char) * 10);
char c = '0' + i;
strncat(str, &c, 1);
strs[i] = str;
}
for (int i = 0; i < 10; i++) {
printf("%s\n", strs[i]);
}
}
I am also interested in instantiating structs the same way without malloc. Is this possible?
A straightforward approach is to declare a two dimensional array like for example
char strs[10][2] = { "" };
for (int i = 0; i < 10; i++) {
strs[i][0] = '0' + i;
}
Here is a demonstration program
#include <stdio.h>
int main( void )
{
enum { N = 10 };
char strs[N][2] = { "" };
for ( int i = 0; i < N; i++ )
{
strs[i][0] = '0' + i;
}
for ( int i = 0; i < N; i++ )
{
printf( "%s ", strs[i] );
}
putchar( '\n' );
}
The program output is
0 1 2 3 4 5 6 7 8 9
Pay attention to that your second program has undefined behavior
char *str = malloc(sizeof(char) * 10);
char c = '0' + i;
strncat(str, &c, 1);
strs[i] = str;
The dynamically allocated array is not initialized. So the call of strncat invokes undefined behavior.
And in the both your programs this call strncat(str, &c, 1); does not build a string. So this call printf("%s\n", strs[i]);again invokes undefined behavior.
Regardless of data type, an object declared at block scope without storage class specifier static* has automatic storage duration. Its lifetime ends when execution of the innermost block containing its declaration terminates. Attempting to access such an object outside its lifetime produces undefined behavior.
If you want an object whose lifetime starts after the beginning of program execution and extends beyond the termination of the innermost block containing the start point, then dynamic allocation is your only choice.
* with static, the object has static storage duration -- the whole run of the program. You can access these via pointer from outside the scope of their identifiers, but for each such declaration there is only object serving the whole execution of the program.
"just wanted to ask if it is possible to avoid malloc."
Yes. The following makes use of Variable Length Arrays, and a function to do this without using calloc or malloc.
Running from the command prompt for example, enter:
your_program_name 10 5<return> to create an array of 10 elements each having room for 4 char plus a terminating null.
void populate_strs(int num, int longest, char sArr[num][longest])
{
for(int i=0;i<num; i++)
{
char c[2] = {0};
c[0] = '0' + (char)i;
c[1] = 0;//null terminate string
strncat(sArr[i], c, 1);//do not need & for string
}
}
int main(int argc, char *argv[])
{
if(argc != 3) printf("Usage error...");
int num_str = atoi(argv[1]);
int max_len = atoi(argv[2]);
char strs[num_str][max_len];
memset(strs, 0, sizeof strs);
populate_strs(num_str, max_len, strs);
for (int i = 0; i < 10; i++) {
printf("%s\n", strs[i]);
}
return 0;
}
And the same is true for an array of struct;
Given this for example:
typdef struct {
int val;
char str;
bool state;
} data_s;
...
int size = 0;
printf("Enter how many array elements of data_s to create.\n");
fscanf(stdin, "%d", &size);
data_s data[size];
memset(data, 0, sizeof data);
//use array of data;
Related
Im just curious if there is anyway of directly converting a char array to a char* array such as:
char charArray[5]={'h','e','l','l','o'};
'Converted' to:
char *pointerArray[5]={"h","e","l","l","o"};
How about this?
#include <stdio.h>
#include <stdlib.h>
char **convert_array(char *arr_in, size_t arr_in_sz)
{
char **arr_out = (char **)malloc(arr_in_sz * sizeof(char *));
for (size_t i = 0; i < arr_in_sz; ++i) {
arr_out[i] = (char *)malloc(2);
arr_out[i][0] = arr_in[i];
arr_out[i][1] = '\0';
}
return arr_out;
}
void free_array(char **arr, size_t arr_sz)
{
for (size_t i = 0; i < arr_sz; ++i)
free(arr[i]);
free(arr);
}
int main()
{
char array_char[] = {'h', 'i'};
char **array_str = convert_array(array_char, sizeof(array_char));
for (size_t i = 0; i < sizeof(array_char); ++i)
printf("%s\n", array_str[i]);
free_array(array_str, sizeof(array_char));
}
You only need a place to store the string literals. You need twice as much memory as for the charArray - to store letters and zero terminating characters, one zero for each letter - twice as much memory. Then initialize pointerarray to point to every second character inside memory. Like so:
#include <stdio.h>
int main() {
char chararray[5]={'h','e','l','l','o'};
char memory[sizeof(chararray) * 2];
for (unsigned i = 0; i < sizeof(chararray); ++i) {
memory[i * 2] = chararray[i];
memory[i * 2 + 1] = '\0';
}
char *pointerarray[5];
for (unsigned i = 0; i < sizeof(chararray); ++i) {
// this loop could me merged with above loop
pointerarray[i] = &memory[i * 2];
}
for (unsigned i = 0; i < 5; ++i) {
printf("%s\n", pointerarray[i]);
}
}
The first one is one dimensional array and secon one is two dimensional. So if you just use pointer like that :
char *pointerArray it means you have an array but you can not assign like in the first example.
I am trying to update string step by step in C. The code i tried is below:
#include <stdlib.h>
#include <stdio.h>
int writech(char **text, char ch) {
**text = ch;
return 1;
}
char *write(int array[], size_t size) {
char *string = (char*)malloc(sizeof(char)*(size+1));
int i, n;
for (i = 0; i < size; ++i) {
n = writech(&string, '0' + array[i]);
string += n;
}
return string;
}
int main() {
int arr[] = { 1, 2, 3, 4, 5 };
char *str = write(arr, sizeof(arr)/sizeof(arr[0]));
printf("%s\n", str);
return 0;
}
Here, write function should update string by calling other function and return updated string at the end. The code compiled and run successfully, though str (at the end of main) is empty after all. Actually, my task is to create string that contain table of some data and return it at the end. Pseudo code for my idea is below:
char *render_table() {
char *table = malloc(sizeof table);
write_header(table);
write_row(table, some_data);
write_row(table, some_data);
write_footer(table)
return table;
}
For implementing this pseudo code I wrote the above code, but not able to update passed string successfully. I know pointers are passed to function as copies, and passed memory of my string (writech(&string) to function, but string not updated still. What am i missing?
P.S. Tweaking with pointers is really struggling for me as beginner in C. What would you suggest?
string is updated. The problem is the pointer string is updated and the information of the beginning of the string is lost. You have to hold the information.
One more point is that terminating null-character must be added to pass the buffer for %s (without specifying length to print).
Also note that casting results of malloc() in C is discouraged.
Try this:
char *write(int array[], size_t size) {
char *string = malloc(sizeof(char)*(size+1));
char *cursor = string;
int i, n;
for (i = 0; i < size; ++i) {
n = writech(&cursor, '0' + array[i]);
cursor += n;
}
writech(&cursor, '\0');
return string;
}
Seems to me that you are making this much more complicated than needed.
Simply do:
for (i = 0; i < size; ++i) {
string[i] = '0' + array[i]);
}
string[i] = '\0';
If for some reason you really want to use the writech function, you can change it to:
void writech(char *text, char ch) {
*text = ch;
}
and call it like:
for (i = 0; i < size; ++i) {
writech(string + i, '0' + array[i]);
}
string[i] = '\0';
but it's really just making a simple task complex.
EDIT due to comment
If you (in your real code) don't know how many chars will be added by a function call, you simply do:
int writeSomethingA(char* str, ... other arguments ...)
{
// update str, e.g. like str[0] = 'a'; str[1] = 'b';
// or strcpy(str, "Some text");
return NumberOfCharAdded;
}
(make similar B and C versions)
and call them like:
char* string malloc(....);
int idx = 0;
idx += writeSomethingA(string + idx, ... other arguments ...);
idx += writeSomethingB(string + idx, ... other arguments ...);
idx += writeSomethingC(string + idx, ... other arguments ...);
string[idx] = '\0';
For starters it is unclear why the function writech
int writech(char **text, char ch) {
**text = ch;
return 1;
}
has the first parameter with the type char ** instead of char *.
The function can be defined like
int writech( char *text, char ch ) {
*text = ch;
return 1;
}
Within the function write the pointer string is being changed in the for loop. So the function returns a pointer that does not point to the beginning of the allocated memory.
Also as you are using the conversion specifier %s to output the character array in main then the array shall contain a string. That is the array shall have contain the terminating zero character '\0'.
The function can be implemented the following way
char * write( const int array[], size_t size ) {
char *string = malloc( size + 1 );
if ( string != NULL )
{
char *p = string;
while ( size-- ) {
p += writech( p, '0' + *array++ );
}
*p = '\0';
}
return string;
}
And you should free the allocated memory before exiting main like
free( str );
Given an array of character strings such as...
char *example[] = {"s", "ss", "sss"};
How can I write a function to count the total number of chars in the array including the terminating characters, without using the standard library for strlen() etc.
Follows is my attempt
int countChars(char *array[], int len)
{
int total = 0, count = 0;
for (int i = 0; i < len; i++)
{
if (array[i] != NULL)
{
while (*array[i] != '\0') {
count++;
}
count++;
}
total += count;
}
return total;
}
An explanation on how char *array[] actually works for access wold be appreciated. I believe that it is supposed to be an array of pointers to strings.
You have to increment the index to consider each of the character.
Something like this:-
for (int i = 0; i < len; i++)
{
if (array[i] != NULL)
{
int j=0,count=0;
while (array[i][j++] != '\0') {
count++;
}
total += count;
}
}
Also reset the count or add to total at the end of all the calculation.
As an answer to your second question:-
char* array[] is basically denoting an array pointers each pointing
to the string literals with which you initialized it.
So once you use array[i] you should now think that it is nothing
other than a pointer to a string literal.
You need to reinitialize the variable count inside the for loop for each processed string and to increase the expression *array[i] inside the while loop.
Also it is better when the function has the return type size_t (size_t is the type that is returned by the standard C function strlen and by the operator sizeof)
The function can look as it is shown in the demonstrative program.
#include <stdio.h>
size_t countChars( const char *array[], size_t n )
{
size_t count = 0;
while ( n-- )
{
if ( array[n] )
{
size_t i = 0;
do { ++count; } while ( array[n][i++] );
}
}
return count;
}
int main(void)
{
const char * example[] = { "s", "ss", "sss" };
printf( "%zu\n", countChars( example, sizeof( example ) / sizeof( *example ) ) );
return 0;
}
The program output is
9
Each element of this array
char *example[] = {"s", "ss", "sss"};
has type char * and is a pointer to the first character of the corresponding string literal.
Since your array contains string constants you should declare it with const:
const char *example[3];
Without const the compiler will not warn you if you try to assign a character to example[i][j]. For the same reason the formal parameter should also be declared with const.
For a pure function with no side effects it is better to name it so that it reflects the result. Therefor I would use charCount instead of countChars (or maybe totalLength). The focus should be on a noun (namely count or length).
Here is my solution:
#include <stdio.h>
#define LEN(a) (sizeof (a) / sizeof (a)[0])
static int CharCount(const char *strings[], int len)
{
int result, i, j;
result = 0;
for (i = 0; i < len; i++) {
j = 0;
while (strings[i][j] != '\0') {
result++;
j++;
}
}
return result;
}
int main(void)
{
const char *strings[] = { "s", "ss", "sss" };
printf("character count: %d\n", CharCount(strings, LEN(strings)));
}
The length macro LEN is very convenient and is the least error prone way to handle array lengths.
Yes char *array[] = {"aa", "bb", "cc"} is an array of pointers to strings.
array[0] points to "aa"
array[1] points to "bb"
array[2] points to "cc"
You probably want this:
int countChars(char *array[], int len)
{
int count = 0;
for (int arrayindex = 0; arrayindex < len; arrayindex++)
{
const char *stringptr = array[arrayindex];
// stringptr will point successively
// to "s", to "ss" and to "sss"
while (*stringptr++)
count++; // increment count until NUL character encountered
count++; // one more for NUL character
}
return count;
}
int main() {
char *example[] = { "s", "ss", "sss" };
int x = countChars(example, 3); // x contains 9 after the call to countChars
// that is 2 + 3 + 4
}
Instead of hard coding 3 you could use sizeof(example) / sizeof(example[0]).
The task was mainly to use pointers to input a string and slice it at places where there is a '\' character and output them in separate lines, using pointers. The program runs fine when I use arrays instead of pointers. However using pointers to store strings give the message "Segmentation fault". The code is as follows :
#include <stdio.h>
#include <stdlib.h>
int main() {
char *name;
char *sep[100];
int i = 0, j = 0, k = 0;
scanf("%[^\n]s", name);
for(i = 0; (*(name+i)) != '\0'; i++) {
if((*(name+i)) == '\\') {
*((*(sep+k))+j) = '\0';
j = 0;
k++;
} else {
*((*(sep+k))+j) = *(name+i);
j++;
}
}
for(i = 0; i <= k; i++) {
printf("%s\n", *(sep+i));
}
return 0;
}
It would be awesome if you could point out what and where the problem is, instead of giving me an alternative solution. TIA.
your pointers are null pointers.you are invoking undefined behavior by using them without assigning them to allocated memory.Allocate memory to them so that you can use them correctly and store words separated by \.Also,you can use [] instead of *.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char name[256];
char *sep[100];
for( int n = 0 ; n < 100 ; n++ )
{
sep[n] = malloc(30*sizeof(char));
}
int i = 0, j = 0, k = 0;
scanf(" %255[^\n]s", name);
for(i = 0; name[i] != '\0'; i++)
{
if( name[i] == '\\')
{
sep[k][j] = '\0';
j = 0;
k++;
}
else
{
sep[k][j] = name[i];
j++;
}
}
sep[k][j] = '\0';
for(i = 0; i <= k ; i++)
{
printf("%s\n",sep[i]);
}
for( int n = 0 ; n < 100 ; n++ )
{
free(sep[n]);
}
return 0;
}
In your code,
scanf("%[^\n]s", name);
name is an unintialized pointer. It does not point to any valid memory location. You need to allocate memory before you can use it.
The same goes out for sep array, too.
You can consider using an array for this purpose or see the man page of malloc() if you want to stick to a pointer.
FWIW, using an unitialized pointer can lead to undefined behavior.
You must allocate space for your pointers to avoid undefined behaviour: you cannot use a pointer without initializing it.
int main() {
char *name = malloc(MAX_DIM_OF_NAME+1);
char *sep[100];
for (int i=0; i<100; i++)
sep[i] = malloc(MAX_DIM_OF_NAME+1);
....
You call scanf with an uninitialized name.
I am new with pointers on C and I am trying to write a function like strcat() but without using it. I developed the following function:
char cat(char *a, char *b) {
int i=0,cont=0,h=strlen(a)+strlen(b);
char c[h]; //new string containing the 2 strings (a and b)
for(i;i<strlen(a);++i) {
c[i] = *(a+i); //now c contains a
}
int j = i;
for(j;j<strlen(b);++j) {
c[j] = *(b+cont); //now c contains a + b
cont++;
}
return c; // I return c
}
And this is how I call the function:
printf("\Concatenazione: %c", cat(A,B));
It is now working because the final result is a weird character. How could I fix the function? Here there's the full main.
char * strcat(char *dest, const char *src)
{
int i;
int j;
for (i = 0; dest[i] != '\0'; i++);
for (j = 0; src[j] != '\0'; j++) {
dest[i+j] = src[j];
}
dest[i+j] = '\0';
return dest;
}
From your implementation it appears that your version of strcat is not compatible with the standard one, because you are looking to allocate memory for the result, rather than expecting the caller to provide you with enough memory to fit the result of concatenation.
There are several issues with your code:
You need to return char*, not char
You need to allocate memory dynamically with malloc; you cannot return a locally allocated array.
You need to add 1 for the null terminator
You need to write the null terminator into the result
You can take both parameters as const char*
You can simplify your function by using pointers instead of indexes, but that part is optional.
Here is how you can do the fixes:
char *cat(const char *a, const char *b) {
int i=0,cont=0,h=strlen(a)+strlen(b);
char *c = malloc(h+1);
// your implementation goes here
c[cont] = '\0';
return c;
}
You are returning a POINTER to the string, not the actual string itself. You need to change the return type to something like "char *" (or something equivalent). You also need to make sure to null terminate the string (append a '\0') for it to print correctly.
Taking my own advice (and also finding the other bug, which is the fact that the second for loop isn't looping over the correct indices), you end up with the following program:
#include <stdio.h>
char *cat(char *a, char *b) {
int i = 0, j = 0;
int cont = 0;
int h = strlen(a) + strlen(b) + 1;
char *result = (char*)malloc(h * sizeof(char));
for(i = 0; i < strlen(a); i++) {
result[i] = a[i];
}
for(j = i; j < strlen(b)+ strlen(a); j++) {
result[j] = b[cont++];
}
// append null character
result[h - 1] = '\0';
return result;
}
int main() {
const char *firstString = "Test First String. ";
const char *secondString = "Another String Here.";
char *combined = cat(firstString, secondString);
printf("%s", combined);
free(combined);
return 0;
}
c is a local variable. It only exists inside the function cat. You should use malloc.
instead of
char c[h];
use
char *c = malloc(h);
Also, you should add the null byte at the end. Remember, the strings in C are null-ended.
h = strlen(a) + strlen(b) + 1;
and at the end:
c[h - 1] = '\0';
The signature of cat should be char *cat(char *a, char *b);
You will get an error of
expected constant expression
for the code line char c[h];. Instead you should be using malloc to allocate any dynamic memory at run-time like::
char* c ;
c = malloc( h + 1 ) ; // +1 for the terminating null char
// do stuff
free( c ) ;
Your corrected code::
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include <stdlib.h>
char* cat(char *a, char *b) {
int i=0,cont=0,h=strlen(a)+strlen(b), j;
char *c;
c = malloc( h+1 ) ;
for(i;i<strlen(a);++i) {
c[i] = *(a+i);
}
j = 0 ;
for(j;j<strlen(b);++j) {
c[i] = *(b+cont);
i++ ;
cont++;
}
c[i] = 0 ;
return c;
}
int main() {
char A[1000],B[1000];
char * a ;
printf("Inserisci la stringa 1: \n");
gets(A);
printf("Inserisci la stringa 2: \n");
gets(B);
a = cat(A,B) ;
printf("\nConcatenazione: %s", a);
free(a) ;
getch();
return 0;
}