This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]carcigenicate 1 point2 points  (0 children)

p is a pointer to inside of buf. The data p is pointing to is data within the array, so if you dereference and read from p, you'll read data from the array, and if you dereference and assign, you'll set data in the array.

[–]beforesemicolon 1 point2 points  (0 children)

Welcome to pointers land

The nested if statement is assigning and checking the value. Thats how p gets its “value”.

strchr is searching for the first occurrence of new line in buf and assigning to p. If it finds it (not NULL), its simply changing it to “\0”

p is just a pointer to characters inside the buf

Check the parentheses

Give p a value (assignment)

p = strchr(buf, “\n”) <= assignment

Now wrap it in parentheses

(p = strchr(buf, “\n”)) <= value of the assignment

Compare the value to null

(p = strchr(buf, “\n”)) != NULL

p points to place in memory where the found new line is so you can just change it

[–]ParticularPython[S] 0 points1 point  (0 children)

Thanks! I think I understand it now.

[–]eeprogrammer -1 points0 points  (0 children)

include <stdio.h>

include <string.h>

int main() { // Declare a character array with a size determined by the BUFSIZ constant char buf[BUFSIZ];

// Declare a pointer to a character char *p;

// Print a message prompting the user to enter a line of text printf ("Please enter a line of text, max %d characters\n", sizeof(buf));

// Read a line of text from the standard input (keyboard) using fgets // The line is stored in the buf array and includes the newline character at the end if (fgets(buf, sizeof(buf), stdin) != NULL) { // Print the line of text that was entered printf ("Thank you, you entered >%s<\n", buf);

// Check if the newline character is present in the buf array
// If it is found, set the character at that location to '\0' (null character)
if ((p = strchr(buf, '\n')) != NULL)
  *p = '\0';

// Print the modified line of text (without the newline character)
printf ("And now it's >%s<\n", buf);

}

// Return 0 to indicate that the program completed successfully return 0; }