The code below reads the contents of the file into a buffer, and then does something with it.
char *getData(){ char *buf = (char*) malloc(100); //write file contents to buf return buf; } char *bar(char *buf){ //do something with buf return buf; } int main(void){ char *result; result = bar(getData()); return 0; }
return buf;line 9 works fine - it returns the whole line. The question is, how can I access individual characters in the buf function string?
return buf;
If you want to access individual characters, you can do it the same way as with any string anywhere else: buf[index](for pointers, ptr[index]exactly the same as *(ptr+index)).
buf[index]
ptr[index]
*(ptr+index)
, malloc, free - . ( , ), .
malloc
free
.
if (buf != NULL) { int i = 0; while (buf[i] != '\0') { // Do Processing ++i; } }
char * - , indexer buf [index] ...
buf [i] ( * (buf + i)) - buf.
(char *) char:
char x = buf[0];
, , , :
char *bar(char *buf) { char newFifthCharacter = 'X'; buf[4] = newFifthCharacter; return buf; }
Please note that you need to be able to perform border checks so that you do not write outside the array. You can use the function strlenin bar, or you can have an integer parameter containing the length. Passing the length is probably better.
strlen
bar
Source: https://habr.com/ru/post/1774136/More articles:How big is a billion triples? - comparisonchrome alternative for firebug evaluation console? - javascriptJBPM - get a list of all tasks - javaCan Delphi tell me the name of the routine that chose the exception? - exceptionUsing Basic SSL Authentication on Windows Phone 7 - windows-phone-7CreateWindowEx () Slow On Windows 7 (sometimes) - performanceIs creating a βdummy recordβ to make the database obey business logic, a good idea or a dumb one? - c #Avoiding space sharing and removing quotes with _spawnvp () - cmultiple functions in document.ready function - javascriptWCF 4.0 SOA Commit as Transcation - c #All Articles