Home > Software engineering >  problem extracting the length of an array of characters from a pointer
problem extracting the length of an array of characters from a pointer

Time:10-29

#include <stdio.h>

typedef struct _Text { 
  char *str; 
  int length; 
  int counter; 
  } *Text;

Text text(char *txtStr){  
  Text txt= malloc(sizeof(*txt));
  txt->str=txtStr; 
  txt->counter=1;
  txt->length=sizeof(*txtStr);
  return txt;
}

int main(void) {
  
  Text txt= text("hello");

  return 0;
}

I need to extract the array length however pointer only returns the size of the first element, how can I determine the length of the array?

CodePudding user response:

A string in C is a series of characters terminated by a NUL (aka '\0'), so you could count how many characters there are like

char *pos = txtStr;
txt->length = 0;
while(*pos != '\0')
  {
  txt->length  ;
  pos  ;
  }

or because life is too long to keep writing code that does things like that, there is a standard function that does all the hard work for you called strlen

txt->length = strlen(txtStr);

Also you want to make a copy of txtStr as its contents may pass out of scope before your newly created Text does...

CodePudding user response:

I would like to add something: After using malloc, you should free that memory when it is not needed anymore. I guess it is just an example code, but it is best to get used to writing that way. And returning an allocated memory could be problematic if not dealt with properly (Good answer for it here: Is it bad manners to return a heap allocated pointer from a function?)

Again, I know your question was purely an example, but it is best to be aware. :)

CodePudding user response:

Use strlen instead of sizeof.

  • Related