Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,026 questions

51,982 answers

573 users

How to represent a string using struct in C

1 Answer

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

typedef struct {
   char*  m_pString ;
   size_t m_iSize ;
} String;

String* String_new(int size) {
   String* pString = malloc(sizeof(String));

   pString->m_iSize = size;
   pString->m_pString = malloc((pString->m_iSize + 1) * sizeof(char));
   pString->m_pString[0] = 0;

   return pString ;
}

void String_delete(String* p) {
    free(p->m_pString);
    free(p);
}

int main(void)
{
    String *p = String_new(16);
    
    strcpy(p->m_pString, "c programming");
    
    puts(p->m_pString);
    printf("%ld\n", strlen(p->m_pString));
    printf("%ld\n", p->m_iSize);
    
    String_delete(p);
    
    return 0;
}
 
 
 
/*
run:
 
c programming
13
16
 
*/

 



answered Mar 7, 2024 by avibootz

Related questions

2 answers 136 views
1 answer 171 views
171 views asked May 6, 2019 by avibootz
3 answers 1,571 views
1 answer 161 views
1 answer 191 views
...